Blocks, Procs and Lambdas Flashcards

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

Little warm up, print the sentence “I’m a block!” 5 times on separate lines, using literal notation and the other way…

A

5.times do
puts “I’m a block!”
end

or

5.times { puts “I’m a block!” }

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

Use a yield statement to a function/method that acts like a method like a collect or map?

A
def double (num)
puts "I'm ready for anything"
yield(num)
puts "Over is over!"
end

double(4) { |num| puts “Double, double #{num * 2}!”}

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

Define a proc

A

floats = [1.2, 1.5 10.6]
round_down = Proc.new { |n| n.floor }
ints = floats.collect(&round_down)
print ints

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

Add a proc to the following code, so the block only has to be written once.

group_1 = [4.1, 5.5, 3.2, 3.3, 6.1, 3.9, 4.7]
group_2 = [7.0, 3.8, 6.2, 6.1, 4.4, 4.9, 3.0]
group_3 = [5.5, 5.1, 3.9, 4.3, 4.9, 3.2, 3.2]
# Complete this as a new Proc
over_4_feet = \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
# Change these three so that they use your new over_4_feet Proc
can_ride_1 = group_1.select { |height| height >= 4 }
can_ride_2 = group_2.select { |height| height >= 4 }
can_ride_3 = group_3.select { |height| height >= 4 }

puts can_ride_1
puts can_ride_2
puts can_ride_3

A
group_1 = [4.1, 5.5, 3.2, 3.3, 6.1, 3.9, 4.7]
group_2 = [7.0, 3.8, 6.2, 6.1, 4.4, 4.9, 3.0]
group_3 = [5.5, 5.1, 3.9, 4.3, 4.9, 3.2, 3.2]

Complete this as a new Proc
over_4_feet = Proc.new do |height|
height >= 4
end

# Change these three so that they use your new over_4_feet Proc
can_ride_1 = group_1.select(&over_4_feet)
can_ride_2 = group_2.select(&over_4_feet)
can_ride_3 = group_3.select(&over_4_feet)

puts can_ride_1
puts can_ride_2
puts can_ride_3

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

Calling a proc with a method isn’t too tricky, however theres an easier way! What is this?

A

hi = Proc.new {puts “Hello!”}

hi.call

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

Whats is the filter iterator method in Ruby and write a short example?

A

my_group = [‘Scott’, ‘Mohit’, ‘Seb’]
long_name = Proc.new { |name| name.length >= 4 }
puts my_group.select(&long_name)

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