7

嗨,我有一个小的 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"]

我需要在开始和停止搜索中使用正则表达式,例如

开始 = "/Yell/"

停止 = "/Ora/"

有没有一种简单的方法可以在 Ruby 中做到这一点?

4

1 回答 1

19

当然,方法index可以接收一个块,这样你就可以做到

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

您甚至可以查看漂亮的 Ruby 的“大小写相等”运算符,并轻松地将字符串和正则表达式作为参数覆盖:

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

然后,如果你传递一个正则表达式 as from,它将执行正则表达式匹配,如果你传递一个String,它将寻找精确的字符串。

于 2012-09-12T09:59:16.790 回答