Blocks Notes Day 2 Flashcards
what are two ways to pass a block into a method?
Brace {…} blocks and [do…end] blocks are functionally equivalent, we just prefer do…end for blocks that contain many lines.
how are blocks and methods similar?
Blocks are somewhat similar to methods in that both can contain lines of code as well as take in parameters. However, an important distinction to make is that the return keyword pertains to methods, not blocks. Let’s take a look at a common pitfall:
# Correct: def double_eles(arr) arr.map do |ele| ele * 2 end end double_eles([1,2,3]) #=> [2,4,6]
# Incorrect: def double_eles(arr) arr.map do |ele| return ele * 2 end end double_eles([1,2,3]) #=> 2
how do you use Methods as Blocks
It is very, very common to have blocks that take an argument and call a single method. For example:
[“a”, “b”, “c”].map { |str| str.upcase } #=> [“A”, “B”, “C”]
[1, 2, 5].select { |num| num.odd? } #=> [1, 5]
Ruby allows us to use cleaner syntax when we have simple blocks that follow the above pattern. Let’s refactor the above example to use this shortcut:
[“a”, “b”, “c”].map(&:upcase) #=> [“A”, “B”, “C”] [1, 5