If you're just starting with Ruby, then you may have seen blocks with curly braces ({...}
) added on a single line (next to methods), for example, like so:
array.inject(0) { | sum, n | sum + n }
These blocks can easily be split into multiple lines, for example, to make the code more readable when additional statements are added:
numbers = [1, 2, 3, 4, 5] numbers.inject(0) { | sum, n | puts "#{sum} + #{n} = #{sum + n}" sum + n } #=> 0 + 1 = 1 #=> 1 + 2 = 3 #=> 3 + 3 = 6 #=> 6 + 4 = 10 #=> 10 + 5 = 15
However, the general convention is to use the do...end
syntax for multi-line blocks (and curly braces for single line blocks):
numbers = [1, 2, 3, 4, 5] numbers.inject(0) do | sum, n | puts "#{sum} + #{n} = #{sum + n}" sum + n end #=> 0 + 1 = 1 #=> 1 + 2 = 3 #=> 3 + 3 = 6 #=> 6 + 4 = 10 #=> 10 + 5 = 15
Please note that blocks with curly braces ({...}
) have a higher precedence than the do...end
syntax.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.