Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the first 3 characters if the first one is a capital letter in Ruby

Tags:

regex

ruby

gsub

I have an array ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC"].

I want to delete the first three characters if the first one is capital in a loop so that I can use each output.

My desired output after the first loop is

["Ab,Aa", "Bb,Bd", "Cc,Cb", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC"]

I am trying in the following but I am stuck.

arr1 =  ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC"]
def eliminatecolumn(arr)
  arr.map do |item| 
    if item[0]=~/[A-Z]/
     item[0..2]=''
    end
  end
end
eliminatecolumn(arr1) 

I get ["", "", "", nil, nil, nil] with this.

I am new to Ruby.

like image 843
shin Avatar asked Dec 02 '25 01:12

shin


1 Answers

Code

a.map { |str| str.sub(/..,/) { |s| (s == s.capitalize) ? "" : s } }
  #=> ["Ab,Aa", "Bb,Bd", "Cc,Cb", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC"]

Explanation

When String#sub is given a block, the match is passed to the block and the block determines the replacement. (nil is passed if there is no match.) For example, when

str = "Ac,Ab,Aa"

the match is

s = "Ac,Ab,Aa"[/..,/] #=> "Ac,"

so

(s == s.capitalize) ? "" : s

becomes

("Ac," == "Ac,") ? "" : "Ac,"

causing "Ac," to be replaced with an empty string. By constrast, if

str => "aA,aC,aD"

the match is

s = "aA,aC,aD"[/..,/] #=> "aA,"

so

(s == s.capitalize) ? "" : s }

becomes

("aA" == "AA") ? "" : "aA" }

causing "aA" to assigned its current value (i.e., left unchanged).

Originally I had str.gsub(/^..,/), with the anchor ^ needed to limit the replacement to the first three characters, but as there was but one (possible) replacement per string, sub could be used, eliminating the need for the anchor.

Alternative

A variant of this solution is the following:

a.map { |str| str.sub(/[A-Z].,/) { |s| s ? "" : s } }

As the block variable is either nil or a string beginning with a capital letter, this eliminates the need to determine, within the block, whether the string is capitalized.

like image 190
Cary Swoveland Avatar answered Dec 03 '25 15:12

Cary Swoveland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!