问题描述
这是我一直在做的: my_array.reject {| elem | elem =〜/ regex /} .each {...}
我觉得这有点儿笨拙的,但我还没有发现任何内建的东西可以让我将它改为 my_array.grepv / regex / {...}
是否有这样的函数?
您知道 Symbol#to_proc
有助于链接?您可以对正则表达式执行相同的操作:
class正则表达式
def to_proc
Proc.new {|串|字符串=〜self}
结束
结束
[Ruby,perl,Perl,PERL]。reject(& / perl / i)
=> [Ruby]
但你可能不应该。 Grep不仅适用于正则表达式 - 您可以像下面这样使用它:
[1,2,three, 4] .grep(Fixnum)
如果你想grep -v,你会实现 Class#to_proc
,这听起来不对。
This is what I've been doing instead:
my_array.reject { |elem| elem =~ /regex/ }.each { ... }
I feel like this is a little unwieldy, but I haven't found anything built in that would let me change it to my_array.grepv /regex/ { ... }
Is there such a function?
You know how Symbol#to_proc
helps with chaining? You can do the same with regular expressions:
class Regexp
def to_proc
Proc.new {|string| string =~ self}
end
end
["Ruby", "perl", "Perl", "PERL"].reject(&/perl/i)
=> ["Ruby"]
But you probably shouldn't. Grep doesn't just work with regular expressions - you can use it like the following
[1,2, "three", 4].grep(Fixnum)
and if you wanted to grep -v that, you'd have to implement Class#to_proc
, which sounds wrong.
这篇关于Ruby相当于grep -v的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!