Blocks, Procs, Lambdas Flashcards
Block
a bit of code that can be executed. does not need a name. Blocks cannot be saved to variables
either use do, end or { } around a block
.collect
method that takes a block and applied the expression in the block to every element in an array without changing the original array
i.e.
my_nums = [1, 2, 3]
my_nums.collect { |num| num ** 2 }
# ==> [1, 4, 9]
my_nums # ==> [1, 2, 3]
.collect!
method that takes a block and applied the expression in the block to every element in an array and changes the original array accordingly
yield
keyword is used to transfer control from a method to a block and then back to the method once executed.
i.e. def yield_test puts "I'm inside the method." yield puts "I'm also inside the method." end
yield_test { puts ">>> I'm butting into the method!" } #Output # I'm inside the method. # >>> I'm butting into the method. # I'm also inside the method.
Proc
syntax: Proc.new
like a block but rather is a block that can be stored in a variable thus reused several times. Calls immediately
square = Proc.new { |x| x ** 2 } # A proc is defined by calling Proc.new followed by a block.
[2, 4, 6].collect!(&square) # When passing a proc to a method, an & is used to convert the proc into a block.
puts [2, 4, 6].collect!(&square) # => [4, 16, 36]
.call
directly calls a proc or a lambda
lambda
on object similar to a proc but it requires a specific number of arguments passed to it. Returns to its calling method rather than returning immediately like in a proc
syntax:
lambda { |param| block }
i.e.
strings = [“leonardo”, “donatello”, “raphael”, “michaelangelo”]
symbolize = lambda {
|string| string.to_sym }
symbols = strings.collect(&symbolize)
print symbols
output:
[:leonardo, :donatello, :raphael, :michaelangelo]
.is_a?
a function that check to see if the parameters in an array are a certain type
i.e.
my_array = [“raindrops”, :kettles, “whiskers”, :mittens, :packages]
Add your code below!
symbol_filter = lambda {
|x| x.is_a? Symbol
}