?
The motivation behind this (less temporary variables) is a non issue to me since the scope of such variables is tiny. In addition, this makes code non idiomatic and harder to read for anyone who hasn't used this gem, and adds another dependency to projects.
I would never stop to think that the x's could be the same. The fact the {} instead of do syntax is used and the fact that the parameter is called 'x' instead of something more descriptive tells me that I shouldn't be concerned with the parameter itself.
After reading the article, Discovered that instead of
["1","2","3"].map{|s| s.to_i}
=> [1, 2, 3]
we can also do
["1","2","3"].map(&:to_i)
=> [1, 2, 3]
This worked for me on Ruby 1.9 out of the box. And I think its an useful shortcut especially when its part of core ruby language & works WITHOUT using any external gems.
This is how languages move forward (or backward). Nice, warrants use and test, but at least people are working to further Ruby. One of the reasons I live on CPAN (as a non-programmer): What new and _useful_ code will I find today? Cheers.
my feeling is: When you are using method_missing hacks to build an object that watches what methods get called on itself, you will eventually get into trouble. There are enough things in Ruby that aren't really methods, like the != operator, which won't do what you expect, and you will produce very confusing bugs, because the code will look correct. The hours that I've seen wasted because people tried to use `x.should != y` in RSpec is enough time to learn a language that supports hygienic macros.
Agree. The goal ought to be to make code more understanble rather than more terse. This short example reads fine either way, but when an expert coder puts this subtle trick in a pile of code noise the replacement developer that has to fix that code months later curses every line of it.
I'm curious about the performance overhead of this vs using traditional syntax with named variables. Looking over the gem, the code is quite terse, but it depends on method_missing, which is notoriously slow. The danger with an abstraction like this is that it can make performance problems difficult to identify since it looks so much like a built-in operator.
I also agree with stuffihavemade in that I don't actually find
It's certainly not "free", but as the method_missing calls are all outside of the loop ((0...1000).map(&X.to_s) calls method_missing only once) the impact on code is minimal.
I've also found using perftools.rb that it's pretty easy to spot ampex — there was one place where we were using it in a tight nested loop and removing that made a measurable difference over tens of thousands of iterations (just as converting &block parameters to implicit yields makes a measurable difference); but mostly the causes of slowness in our app have not been this.