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
Access Instance Variable from Outside the Class
What Do the Different Brackets in Ruby Mean
What Is the Best/How to Validate an Email Address in Ruby
What Is the Modern Way to Structure a Ruby Gem
Cannot Load Such File -- Readline (Loaderror) When Running Heroku Create --Stack Cedar
How to Access (Devise) Current_User in a Rspec Feature Test
Is There a Simple Way to Get Image Dimensions in Ruby
What Is the "Equals Greater Than" Operator => in Ruby
One Liner in Ruby for Displaying a Prompt, Getting Input, and Assigning to a Variable
How to See the Dependency Tree Just from Gemfile
Given the Session Key and Secret, How to Decrypt Rails Cookies
Iconv Deprecation Warning with Ruby 1.9.3
Why Does Accessing a Ssl Site with Mechanize on Windows Fail, But on MAC Work