Blocks, Procs and Lambdas Flashcards
Little warm up, print the sentence “I’m a block!” 5 times on separate lines, using literal notation and the other way…
5.times do
puts “I’m a block!”
end
or
5.times { puts “I’m a block!” }
Use a yield statement to a function/method that acts like a method like a collect or map?
def double (num) puts "I'm ready for anything" yield(num) puts "Over is over!" end
double(4) { |num| puts “Double, double #{num * 2}!”}
Define a proc
floats = [1.2, 1.5 10.6]
round_down = Proc.new { |n| n.floor }
ints = floats.collect(&round_down)
print ints
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
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
Calling a proc with a method isn’t too tricky, however theres an easier way! What is this?
hi = Proc.new {puts “Hello!”}
hi.call
Whats is the filter iterator method in Ruby and write a short example?
my_group = [‘Scott’, ‘Mohit’, ‘Seb’]
long_name = Proc.new { |name| name.length >= 4 }
puts my_group.select(&long_name)