加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用Regex表达式搜索Ruby数组

发布时间:2020-12-16 21:20:17 所属栏目:百科 来源:网络整理
导读:嗨,我有一个小的 ruby函数,分割出一个 Ruby数组,如下所示: – def rearrange arr,from,to sidx = arr.index from eidx = arr.index to arr[sidx] = arr[sidx+1..eidx]endarr= ["Red","Green","Blue","Yellow","Cyan","Magenta","Orange","Purple","Pink","W
嗨,我有一个小的 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",["Cyan","Orange"],"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'

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读