Blocks Notes Day 2 Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

what are two ways to pass a block into a method?

A

Brace {…} blocks and [do…end] blocks are functionally equivalent, we just prefer do…end for blocks that contain many lines.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

how are blocks and methods similar?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

how do you use Methods as Blocks

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly