Blocks/Lambdas Flashcards
How to send and run block (3 ways to invoke)?
=> hello
def hello(a, &block)
a.call
yield
block.call
end
a = -> () { p ‘hello’}
hello(a) { p ‘hello’ }
# => hello
# => hello
How to send and run block with params? ( 2 ways )
=> 1 + 2
def hello
yield(1,2)
end
hello { |a,b| p “#{a} + #{b}” }
def hello(&block)
block.call(1,2)
end
hello { |a,b| p “#{a} + #{b}” }
How to check that the block has been sent?
use block_given?
def run_block
if block_given?
yield
end
end
run_block { p ‘My name’ }
Why we shouldn’t use return inside our block?
=> ‘Start’ 2
‘return’ will return from the method, not from the block
def run_block
p ‘Start’
yield
p ‘End’
end
def hello
run_block { return 1 + 1 }
end
hello
# => ‘End’ doesn’t invoke
What is .tap operation?
tap add some operation after result is ready in background
(1+1).tap { |a| puts a; 10 }
# puts 2
# returns 2
What is .then operation?
The is the same as tap but return actually calculated value in the block
(1+1).then { |a| puts a; 10 }
# return 10
What are 4 ways to invoke lambda?
my_lambda = -> { puts “Lambda called” }
my_lambda.call
my_lambda.()
my_lambda[]
my_lambda.===
What are the differences between proc and lymbda
. 1 Lambdas are defined with -> {} and procs with Proc.new {} .
A lambda is just a special Proc object.
itself.
def call_proc
puts “Before proc”
my_proc = Proc.new { return 2 }
my_proc.call
puts “After proc”
end
p call_proc
# Prints “Before proc” but not “After proc”
t = Proc.new { |x,y| puts “I don’t care about arguments!” }
t.call
# “I don’t care about arguments!”
How does [“cat”, “dog”].map(&:upcase) work?
1. converts to proc
Using the ampersand symbol like this calls the to_proc method on whatever object is on the right.
So when you do %w(foo bar).map(&:upcase) .
What &:upcase is really doing is this: Proc.new { |word| word.upcase }
# 2. says that this is not an argument but block
def hello(&block)
block.call(‘abc’)
end
p hello(&:upcase)
Is it possible to invoke a method using .call?
def hello
p ‘hello’
end
a = method :hello
a.call
How to send a method to [].map(&method_name) ?
def multiply2
proc do |number|
number * 2
end
end
p [1,2,3].map(&multiply2)
# [2,4,6]
How to send an instance of class to [].map(&instance_of_class) ?
we need to define .to_proc method on the class
class Hello
def to_proc
proc do |number|
number * 2
end
end
end
p [1,2,3].map(&Hello.new)
What is yield_self method?
The same as tap, but return values inside the block istead.
5.yield_self { |x| x * x }
# 25