使用Regex表达式搜索Ruby数组
嗨我有小ruby函数,拆分Ruby数组如下: –
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"]
我需要在我的开始使用正则表达式并停止搜索,例如
开始=“/大喊/”
停止=“/ Ora /”
有没有一种简单的方法在Ruby中做到这一点?
当然,方法index
可以接收一个块,这样就可以了
sidx = arr.index{|e| e =~ from }
您甚至可以查看Ruby的’case equality’运算符,并轻松地将字符串和正则表达式作为参数覆盖:
sidx = arr.index{|e| from === e} # watch out: this is not the same as 'e === from'
然后,如果你传递一个正则表达式,它将执行正则表达式匹配,如果你传递一个String
,它将寻找精确的字符串。