Blocks and Procs and Lambdas
suggest changeVersions
[{“Name”:“2.0”,“GroupName”:null},{“Name”:“2.1”,“GroupName”:null},{“Name”:“2.2”,“GroupName”:null},{“Name”:“2.3”,“GroupName”:null}]
Syntax
- Proc.new(block)
- lambda { |args| code }
- ->(arg1, arg2) { code }
- object.to_proc
- { |single_arg| code }
- do |arg, (key, value)| code end
Remarks
Be careful about operator precedence when you have a line with multiple methods chained, like:
str = "abcdefg"
puts str.gsub(/./) do |match|
rand(2).zero? ? match.upcase : match.downcase
end
Instead of printing something like abCDeFg
, like you’d expect, it prints something like #<Enumerator:0x00000000af42b28>
– this is because do ... end
has lower precedence than methods, which means that gsub
only sees the /./
argument, and not the block argument. It returns an enumerator. The block ends up passed to puts
, which ignores it and just displays the result of gsub(/./)
.
To fix this, either wrap the gsub
call in parentheses or use { ... }
instead.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents