Searching Ruby Arrays with Regex expressions

2020-07-10 11:41发布

问题:

Hi I have small ruby function that splits out a Ruby array as follows:-

def rearrange arr,from,to
  sidx = arr.index from
  eidx = arr.index to
  arr[sidx] = arr[sidx+1..eidx]
end

arr= ["Red", "Green", "Blue", "Yellow", "Cyan", "Magenta", "Orange", "Purple", "Pink",    "White", "Black"]
start = "Yellow"
stop = "Orange"

rearrange arr,start,stop
puts arr.inspect
#=> ["Red", "Green", "Blue", ["Cyan", "Magenta", "Orange"], "Cyan", "Magenta", "Orange", "Purple", "Pink", "White", "Black"]

I need use use a regex expression in my start and stop searches e.g.

Start = "/Yell/"

Stop = "/Ora/"

Is there an easy way yo do this in Ruby?

回答1:

Of course, method index can receive a block, so that you could do

sidx = arr.index{|e| e =~ from }

You can even check out nice Ruby's 'case equality' operator and easily cover both strings and regexes as arguments:

sidx = arr.index{|e| from === e} # watch out: this is not the same as 'e === from'

Then, if you pass a regex as from, it will perform regex match, and if you pass a String, it would look for exact string.