I have a list:
list = ["mango", "apple", "pearl", "peach"]
and I need to use yield so that this line of code:
answer = myIndexOf(list) {|e| e == "apple"}
returns the value 1, which is the index of "apple" in the array.
I have this, but I don't understand yield.
def myIndexOf(list)
yield answer if block_given?
result = list.index(answer)
return answer
end
Can anyone shed some light on this?
Understanding yield/blocks is actually quite simple. Just think of blocks as methods and yield as a way of calling those methods.
Imagine that, instead of block, you have this
def is_this_the_right_item?(item)
item == "apple"
end
def myIndexOf(a_list)
# your implementation goes here
end
answer = myIndexOf(list)
Can you code this implementation of myIndexOf? It doesn't involve yielding at all. And when you're done, you simply bring the block back to the invocation of myIndexOf and replace all calls to is_this_the_right_item? with yield.
yield calls the block.
The following functions are "the same"
def example()
raise unless block_given?
yield 1
yield 2
yield 3
end
def example(&block)
block.call(1)
block.call(2)
block.call(3)
end
Both can be called as follow
example { |each| puts each }
Both will then output
1
2
3
Hope that helps to shed light on higher-order functions in Ruby.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With