【问题标题】:Searching Ruby Arrays with Regex expressions使用正则表达式搜索 Ruby 数组
【发布时间】:2012-09-12 09:55:01
【问题描述】:

您好,我有一个小的 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 中有一个简单的方法吗?

【问题讨论】:

    标签: ruby regex arrays


    【解决方案1】:

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

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

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

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

    然后,如果您将正则表达式作为from 传递,它将执行正则表达式匹配,如果您传递String,它将查找确切的字符串。

    【讨论】:

    • 太棒了!非常好。完美运行。感谢您的反馈。
    • @user1513388 如果解决了您的问题,请accept the answer
    猜你喜欢
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    相关资源
    最近更新 更多