B.5 Single line blocks
Often, we only have one line of code within our do
/end
blocks:
8, 3, 1, 4, 3, 9]
numbers = [
do |num|
numbers.select 3
num > end
# => [8, 4, 9]
If you wanted to, you could fit it all on one line:
8, 3, 1, 4, 3, 9]
numbers = [
do |num| num > 3 end
numbers.select
# => [8, 4, 9]
You can also replace the do
with an opening curly bracket ({
) and the end
with a closing curly bracket (}
):
8, 3, 1, 4, 3, 9]
numbers = [
3 }
numbers.select { |num| num >
# => [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:
8, 3, 1, 4, 3, 9]
numbers = [
3 }.sort
numbers.select { |num| num >
# => [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.