搜索红宝石阵列与正则表达式前pressions [英] Searching Ruby Arrays with Regex expressions

查看:132
本文介绍了搜索红宝石阵列与正则表达式前pressions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一个打出一个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"]

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

I need use use a regex expression in my start and stop searches e.g.

开始=/呐喊/

停止=/奥拉/

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

Is there an easy way yo do this in Ruby?

推荐答案

当然,方法的 首页 可以接收模块,让你可以做

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.

这篇关于搜索红宝石阵列与正则表达式前pressions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆