I’m trying to figure out how to iterate through an array in Ruby and perform actions based upon the values (and figure out how to use yield. Below is the code I have so far, however this is not working. Can someone help point me in the right direction?
each_odd("Odd")
def each_odd
array = [1, 2, 3, 4]
array.map {|x|
if (x % 2 != 0) do x = yield
else x = "Even"
end}
end
I am expecting this to return the following array: ["Odd", "Even", "Odd", "Even"]
To use yield you have to pass a block.
And you can use
{}blocksOr
do .. endblocksAnd here is how to implement the method
When called
yieldit will evaluate what’s inside the block and return it to the context, also you can pass parameters to the block like so:and then you could do something like