Ampex - concise readable Ruby blocks
cirw.in
cirw.in
[10, 11, 12].map(&X.to_s(16))
more readable than [10, 11, 12].map({|x| x.to_s(16)})
?
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. [10, 11, 12].map{|x| x.to_s(16)}
[:baz, :bam, :bar].map{|x| x.to_s(16)}
At least for me, I tie the 'x's together in my head; so I have to concentrate to realise that there are two different 'x's.I've not done any formal research into this, it would be interesting to see whether there's actually a perceivable difference between the two styles.
["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. ruby-1.9.3-p0 :001 > double = -> x { x * 2 }
=> #<Proc:0x000001009236e0@(irb):1 (lambda)>
ruby-1.9.3-p0 :002 > double[2]
=> 4
ruby-1.9.3-p0 :003 > [1].map(&double)
=> [2] [* _ 2]
becomes (lambda (x) (* x 2))Here's the Ruby examples in perl6 (all work in Rakudo)...
[10, 11, 12].map: (* + 87).chr;
@owners.map: *<name>;
"alpha\nbeta\ngamma\n".lines.map: *.uc;
NB. A limited version of Whatever-star is also available for perl5 - https://metacpan.org/module/WhateverWriting these libraries is a great way to learn about ruby, but avoid them in production - there's usually a safer way. (For a simple example of dangerous-methodmissing-hack verus sane metaprogramming to accomplish the same task, compare http://andand.rubyforge.org/ with http://api.rubyonrails.org/classes/Object.html#method-i-try )
I also agree with stuffihavemade in that I don't actually find
(&X.method(bar))
any more clear than { |x| x.method(bar) }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.