Question | Click to View Answer |
In the following example, the Array#map method is passed the following code block: {|number| number * 2} Describe how the code block works in the following example. [1, 2, 3].map do |number|
number * 2
end
|
Code blocks are chunks of code that can be added as the last argument of a method. Code blocks can be delimited by { } or do / end. In this example, each element of the [1, 2, 3] array object is iterated over and "yielded" to the code block. The first element (1) is yielded to the code block and assigned to the block variable "number". The map() method adds the result of the code block to a new array. This same process is followed for the rest of the elements in the array (2 and 3). |
What does the following code print? def cool
return yield
end
p cool {"yes!"}
|
"yes!"
The yield keyword instructs Ruby to execute the code in the block. In this example, the block returns the string "yes!". An explicit return statement was used in the cool() method, but this could have been implicit as well. |
What does the following code print? def nice
yield("captain", "planet")
end
nice do |first_name, last_name|
"#{first_name} #{last_name}"
end
|
"captain planet"
The yield statement has two parameters ("captain" and "planet") that are passed to the block as block variables (first_name and last_name) when the block is yielded. Passing different blocks to the nice() method will yield different results: nice do |master, location|
"Is someone the #{master} of our #{location}?"
end # returns "Is someone the captain of our planet?"
|
What does the following code print? def like_map(array)
result = []
array.each do |element|
result << (yield element)
end
result
end
result = like_map([1, 2, 3]) do |number|
number * 2
end
p result
|
[2, 4, 6]
The like_map() method takes and array and block as arguments. like_map() iterates over each element of the array, yields the code block, and appends the result to the result array. like_map() behaves like the Array#map method. |
Add a my_map() method to the Array class that behaves the same as the Array#map method. |
class Array
def my_map
result = []
self.each do |element|
result << ( yield element )
end
result
end
end
result = [1, 2, 3].my_map do |x|
x * 2
end
p result # returns [2, 4, 6]
|
What does the following code print? def add(x, y)
return(x + y)
end
result = add(4, 5) do
puts "Hey mom"
end
p result
|
9
The add() method is passed a code block, but it doesn't require the code block. When methods are passed a code block but don't require the code block, the code block is simply ignored. |
What does the following code print? p ["tommy", "chuckie"].map(&:upcase)
|
["TOMMY", "CHUCKIE"]
This example uses the shorthand symbol to proc notation to apply the upcase() method to every element in the array. The shorthand notation achieves the same result as the explicit notation: ["tommy", "chuckie"].map { |name| name.upcase }
|