Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching Ruby Arrays with Regex expressions

Tags:

arrays

regex

ruby

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?

like image 993
user1513388 Avatar asked Sep 12 '12 09:09

user1513388


People also ask

What kind of regex does Ruby use?

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.

What does =~ mean in Ruby regex?

=~ 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.

How do you check if an array is equal in Ruby?

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.


1 Answers

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.

like image 184
Mladen Jablanović Avatar answered Oct 05 '22 09:10

Mladen Jablanović