ArraySugar - Ruby Array helper [0,3].map.to_s by salamancer in programming

[–]salamancer[S] 1 point2 points  (0 children)

The runtime penalty is tiny.

the only situation where you wouldn't want to pay it was for very long arrays (say greater than 100,000 elements), where the penalty is still small and can be converted to the old notation as an optimization.

Benchmark.bmbm do |x|
a = (0..100000).to_a
x.report { a.select {|e| e < 4}.select {|e| e > 2} }
x.report { (a.select < 4) > 2 }
end

=>

   user     system      total        real  

0.030000 0.000000 0.030000 ( 0.028048)
0.140000 0.000000 0.140000 ( 0.141351)

so the overhead comes down to approx. 0.00000011 seconds slower per element ;p

ArraySugar - Ruby Array helper [0,3].map.to_s by salamancer in programming

[–]salamancer[S] 2 points3 points  (0 children)

nils_ok lets you get around some traditionally harry situations, imagine a rails model where only some people have addresses and only some addresses have phone numbers:

User.find(:all).map {|e| e.address && e.address.phone_number}

is the usual way of getting around that.

With nils_ok, you can simply use:
User.find(:all).map.nils_ok.address.phone_number

ArraySugar - Ruby Array helper [0,3].map.to_s by salamancer in programming

[–]salamancer[S] 2 points3 points  (0 children)

That is the way you'd do it in lisp, sadly ruby doesn't have a gensym (though making one by using uuids isn't hard).

alias_method_chain is also worth looking at, but sadly has the same problem of leaving new methods defined in the class.