my_nums = [1, 2, 3]
my_nums.collect { |num| num ** 2 }
# ==> [1, 4, 9]
20)
fibs = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
# Add your code below!
doubled_fibs = fibs.collect do |fib|
fib * 2
end
21)
def block_test
puts "We're in the method!"
puts "Yielding to the block..."
yield
puts "We're back in the method!"
end
block_test { puts ">>> We're in the block!" }
22)
def double(num)
yield(5)
end
double(3) {|n| n*2}
23)proc
floats = [1.2, 3.45, 0.91, 7.727, 11.42, 482.911]
# Write your code below this line!
round_down=Proc.new {|f| (f-0.5).round}
# Write your code above this line!
ints = floats.collect(&round_down)
--------------------
[1, 2, 3].collect!(&cube)
# ==> [1, 8, 27]
[4, 5, 6].map!(&cube)
# ==> [64, 125, 216]
(The
.collect!
and
.map!
methods do the exact same thing.)
--------------------------
24)
def greeter
yield
end
phrase=Proc.new {puts "Hello there!"}
greeter(&phrase)
25)
hi=Proc.new {puts "Hello!"}
hi.call
26)
numbers_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
strings_array = numbers_array.map(&:to_s)
27)Lambda —think about the differences between lambda and proc;
def batman_ironman_proc
victor = Proc.new { return "Batman will win!" }
victor.call
"Iron Man will win!"
end
puts batman_ironman_proc
def batman_ironman_lambda
victor = lambda { return "Batman will win!" }
victor.call
"Iron Man will win!"
end
puts batman_ironman_lambda
27)
my_array = ["raindrops", :kettles, "whiskers", :mittens, :packages]
# Add your code below!
symbol_filter=lambda{|c| return c.is_a? Symbol}
symbols=my_array.select(&symbol_filter)
28)Camparison of block, proc, and lambda
block:
odds_n_ends = [:weezard, 42, "Trady Blix", 3, true, 19, 12.345]
ints=odds_n_ends.select{|a| a.is_a? Integer}
proc:
ages = [23, 101, 7, 104, 11, 94, 100, 121, 101, 70, 44]
# Add your code below!
under_100=Proc.new{|n| n<100}
youngsters=ages.select(&under_100)
lambda:
crew = {
captain: "Picard",
first_officer: "Riker",
lt_cdr: "Data",
lt: "Worf",
ensign: "Ro",
counselor: "Troi",
chief_engineer: "LaForge",
doctor: "Crusher"
}
# Add your code below!
first_half=lambda{|k, v| return v<"M"}
a_to_m=crew.select(&first_half)