Ruby: Proc.New { 'Waffles' } VS. Proc { 'Waffles' }

Ruby: Proc.new { 'waffles' } vs. proc { 'waffles' }

From Metaprogamming Ruby Page 113.

In Ruby 1.8, Kernel#proc() is actually a synonym for Kernel#lambda(). Because of loud protest from programmers, Ruby 1.9 made proc() a synonym for Proc.new() instead.

Are there Ruby precedence issues with using Proc.call vs. Proc.[]?

The #call technique allows the operator precedence to potentially obscure intent:

p = Proc::new do |a1| Proc::new do |a2| "#{a1.inspect}:#{a2.inspect}" end end
p.call([1,2,3]).call [1]
=> => "[1, 2, 3]:[1]"
p.call [1,2,3][1]
=> #<Proc:0x7ffa08dc@(irb):1>
p.call([1,2,3])[1]
=> "[1, 2, 3]:1"
p[[1,2,3]][[1]]
=> "[1, 2, 3]:[1]"

The [] syntax makes the syntactic association of the arguments to the method more robust, but you'd achieve the same effect by putting parentheses around the arguments to Proc#call.

When to use a lambda in Ruby on Rails?

http://augustl.com/blog/2008/procs_blocks_and_anonymous_functions/ has a run-down of what blocks/procs/lambdas are, how you can use them, and how they compare to functions in other languages. It definitely answers your question.

Do be aware that the last section 'A note on lambdas' mentions a point that is only true in Ruby 1.8 and changed in 1.9 - Ruby: Proc.new { 'waffles' } vs. proc { 'waffles' }

Include a module with or without send, is there any difference?

They are almost identical.

The difference is that if SomeClass#include is private, the latter will still be able to call it due to the nature of Object#send

If SomeClass#include was private and you went with the former, it would raise an error.

So the advantage of using the latter is that you can include a module no matter what the visibility is. (Whether or not you actually believe accessing private methods is the "right" thing to do is another story. It certainly gives you tremendous power).



Related Topics



Leave a reply



Submit