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?
A regular expression is a sequence of characters that define a search pattern, mainly for use in pattern matching with strings. Ruby regular expressions i.e. Ruby regex for short, helps us to find particular patterns inside a string. Two uses of ruby regex are Validation and Parsing.
=~ is Ruby's pattern-matching operator. It matches a regular expression on the left to a string on the right. If a match is found, the index of first match in string is returned. If the string cannot be found, nil will be returned.
Arrays can be equal if they have the same number of elements and if each element is equal to the corresponding element in the array. To compare arrays in order to find if they are equal or not, we have to use the == operator.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With