4 ms·
I'm not a Rubyist, but isn't overloading operators to do things completely unrelated to their normal semantics (like most of the examples here) generally a terr
by BruceIV 12y ago
I'm not a Rubyist, but isn't overloading operators to do things completely unrelated to their normal semantics (like most of the examples here) generally a terrible thing to do?
- bradleyland 12y agoThese are just easy to understand examples. I don't know any Rubyists who would actually define these methods in exactly this way. If you look at the Ruby StdLib, you'll see that, most of the time, libraries implement operators in a way that is consistent with the spirit of canonical methods. For example, in Unix, a network socket is abstracted in a way that is similar to a file. You read/write from it in similar ways. This is an abstraction pattern. Ruby also has patterns. Lots of them, actually. 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/Array.html#method-i-map http://www.ruby-doc.org/core-2.1.3/Symbol.html#method-i-to_proc 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-as-unary.html 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.