Chaining methods using Symbol#to_proc shorthand in Ruby?

老子叫甜甜 提交于 2019-12-17 20:05:46

问题


I'm wondering is there a way we can chain a method using (&:method)

For example:

array.reject { |x| x.strip.empty? }

To turn it into:

array.reject(&:strip.empty?)

I prefer the shorthand notation, due to its readability.


回答1:


No, there's no shorthand for that. You could define a method:

def really_empty?(x)
  x.strip.empty?
end

and use method:

array.reject(&method(:really_empty?))

or use a lambda:

really_empty = ->(x) { x.strip.empty? }
array.reject(&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.

However, since you're using Rails, you could just use blank? instead of .strip.empty?:

array.reject(&:blank?)

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 nils 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.




回答2:


It would be quite nice to write the above like that but it's not a supported syntax, the way that you would want to chain methods using the to_proc syntax (&:) is like so:

.map(&:strip).reject(&:empty?)




回答3:


You can do it with the ampex gem:

require 'ampex'
array.reject &X.strip.empty?


来源:https://stackoverflow.com/questions/9460204/chaining-methods-using-symbolto-proc-shorthand-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!