Question:
arr = ["foo", "bar"].map{ |s| s.upcase }
This code can be shortened as follows:
arr = ["foo", "bar"].map(&:upcase)
Then,
arr2 = ["foo", "bar"].map{ |s| my_method(s) }
Is there a way to shorten such code?
If not, is there a reason that this writing method itself is not ruby-like in the first place?
(Is it better to make it in the form of s.my_method by duck typing or creating a class for myself that inherits the corresponding class?)
Answer: Answer:
It may be the same as the content of this article I wrote for Qiita earlier.
When processing arrays in sequence, use "& method (: name)" instead of calling the method directly
When processing arrays in sequence, use "& method (: name)" instead of calling the method directly
It's more common to write blocks normally, but you can also pass arguments like & method (: name).
When calling normally
def process_users
users.each do |user|
process_user(user)
end
end
def process_user(user)
send_mail_to(user)
user.mail_sent_at = Time.now
user.save
end
When calling in the format of & method (: name)
def process_users
users.each(&method(:process_user))
end
def process_user(user)
send_mail_to(user)
user.mail_sent_at = Time.now
user.save
end