Blocks, Procs, Lambdas Flashcards

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

Block

A

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

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

.collect

A

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]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

.collect!

A

method that takes a block and applied the expression in the block to every element in an array and changes the original array accordingly

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

yield

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Proc

A

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]
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

.call

A

directly calls a proc or a lambda

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

lambda

A

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]

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

.is_a?

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
}

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