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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, there’s no shorthand for that. You could define a method:
and use
method:or use a lambda:
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?:Note that
nil.blank?is true whereasnil.strip.empty?just hands you an exception so they’re not quite equivalent; however, you probably want to rejectnils as well so usingblank?might be better anyway.blank?also returns true forfalse,{}, and[]but you probably don’t have those in your array of strings.