Alternative Block Syntaxes
Get to know some alternative syntaxes that we use for blocks in Ruby.
We'll cover the following...
An alternative way to define blocks
Along with the syntax shown before, using do and end, Ruby comes with an alternative syntax, which uses curly braces to define a block.
These two statements do exactly the same thing:
5.times doputs "Oh, hello!"end5.times { puts "hello!" }
Both statements define a block, which is passed to the times method. Both blocks contain a single line of code.
Remember: Blocks can be defined by enclosing code in do and end or by using curly braces ({}).
Which syntax to use
In the Ruby community, we use curly braces if we have a single-line block and it fits nicely on the same line, like it does in our example.
Whenever we need more than one line in our block, we use the do and end syntax. Programmers sometimes also use the do and end syntax when they feel it makes the code more readable.