How exactly does it work?

Technology CommunityCategory: RubyHow exactly does it work?
VietMX Staff asked 3 years ago

In Ruby code, you quite often see the trick of using an expression like as a shorthand form of { |element| element.method_name }. How exactly does it work?

When a parameter is passed with & in front of it (indicating that is it to be used as a block), Ruby will call to_proc on it in an attempt to make it usable as a block. Symbol#to_proc quite handily returns a Proc that will invoke the method of the corresponding name on whatever is passed to it, thus enabling our little shorthand trick to work.