Ruby’s Unary Operators and How to Redefine Their Functionality
rubyinside.com
rubyinside.com
For example, many Ruby objects accept a block. The ampersand unary operator is used in a particularly common pattern that interacts with methods where a block would normally be passed.
Imagine you have an object that is implemented as a collection of items; like a collection of query results, wrapped in an object. Let's also imagine you want to call a method on each of the items. In Ruby there are two simple ways to do this. The example below uses an Array, upon which many common patterns are based [1].
1) Using a simple map function, which passes the receiver as an argument to a block:
["Hello", "WORLD!"].map { |x| x.downcase }
#=> ["hello", "world"]
2) Using the unary operator of the Symbol class to pass a proc: ["Hello", "WORLD"].map(&:downcase)
#=> ["hello", "world!"]
The second example uses a pattern combining #map from Array and #to_proc from Symbol. This looks like magic the first time you see it, but it's actually pretty simple to follow when you look at the two examples side by side.Ref:
http://www.ruby-doc.org/core-2.1.3/Array.html#method-i-map
http://www.ruby-doc.org/core-2.1.3/Symbol.html#method-i-to_p...
The article linked in the submission is definitely worth a look. My explanations are obtuse, because I'm still an amateur after all these years.
http://weblog.raganwald.com/2008/06/what-does-do-when-used-a...
1: Actually, Array includes Enumerable, which is the specific module where many of Ruby's common patterns are implemented, but I didn't want the language to become too dense.