在 Ruby 中使用 Symbol#to_proc 速记链接方法? [英] Chaining methods using Symbol#to_proc shorthand in Ruby?
问题描述
我想知道有没有一种方法可以使用 (&:method) 链接一个方法
I'm wondering is there a way we can chain a method using (&:method)
例如:
array.reject { |x| x.strip.empty? }
把它变成:
array.reject(&:strip.empty?)
我更喜欢简写符号,因为它的可读性.
I prefer the shorthand notation, due to its readability.
推荐答案
不,没有简写.你可以定义一个方法:
No, there's no shorthand for that. You could define a method:
def really_empty?(x)
x.strip.empty?
end
并使用method
:
array.reject(&method(:really_empty?))
或使用 lambda:
or use a lambda:
really_empty = ->(x) { x.strip.empty? }
array.reject(&really_empty)
但除非您在足够多的地方使用 really_empty?
以便拆分逻辑是有意义的,否则我不会称它们中的任何一个更好.
but I wouldn't call either of those better unless you have a use for really_empty?
in enough places that splitting up the logic makes sense.
但是,由于您使用的是 Rails,您可以只使用 blank?
而不是 .strip.empty?
:
However, since you're using Rails, you could just use blank?
instead of .strip.empty?
:
array.reject(&:blank?)
注意 nil.blank?
是真的,而 nil.strip.empty?
只是给你一个异常,所以它们并不完全相同;但是,您可能也想拒绝 nil
,因此无论如何使用 blank?
可能会更好.blank?
也会为 false
、{}
和 []
返回 true,但您可能没有这些在你的字符串数组中.
Note that nil.blank?
is true whereas nil.strip.empty?
just hands you an exception so they're not quite equivalent; however, you probably want to reject nil
s as well so using blank?
might be better anyway. blank?
also returns true for false
, {}
, and []
but you probably don't have those in your array of strings.
这篇关于在 Ruby 中使用 Symbol#to_proc 速记链接方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!