8

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 Answer 1

20

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Superb! Very nice. Works perfectly. Thanks for the feedback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.