B.5 Single line blocks

Often, we only have one line of code within our do/end blocks:

numbers = [8, 3, 1, 4, 3, 9]

numbers.select do |num|
  num > 3
end

# => [8, 4, 9]

If you wanted to, you could fit it all on one line:

numbers = [8, 3, 1, 4, 3, 9]

numbers.select do |num| num > 3 end

# => [8, 4, 9]

You can also replace the do with an opening curly bracket ({) and the end with a closing curly bracket (}):

numbers = [8, 3, 1, 4, 3, 9]

numbers.select { |num| num > 3 }

# => [8, 4, 9]

This can get confusing, because now we’re overloading the curly braces ({}) for more than one purpose: Hash literals and blocks. However, it’s a very common style so you should get used to figuring out which one it is from the context. If the curly braces are next to a method and there are no key/value pairs, then it’s a block, not a Hash.

This style is most often used when chaining more methods:

numbers = [8, 3, 1, 4, 3, 9]

numbers.select { |num| num > 3 }.sort

# => [4, 8, 9]

Ruby wants developers to be happy, so it gives them lots of options — this is a double-edged sword! It means we can be expressive, but it also means we need to be able to parse many different styles when reading other people’s writing. As beginners, it can be frustrating; but in the long-run, you’ll appreciate it.