fwefwf
fwefwf

Reputation: 141

How do I use `yield`?

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?

Upvotes: 3

Views: 1881

Answers (3)

Sagar Pandya
Sagar Pandya

Reputation: 9497

Further to Sergio's answer:

list = ["mango", "apple", "pearl", "peach"]

def myIndexOf(a_list)
  a_list.index { |e| yield e }
end

p answer = myIndexOf(list) { |e| e ==  'apple' }
#=> 1

I'm submitting because I thought this was a tricky exercise and reverse engineering the answer may help you.

Upvotes: 0

akuhn
akuhn

Reputation: 27793

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.

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

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.

Upvotes: 7

Related Questions