我如何使用`yield`?

时间:2017-07-29 21:25:41

标签: ruby yield

我有一个清单:

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

我需要使用yield以便这行代码:

answer = myIndexOf(list) {|e| e == "apple"}

返回值1,它是数组中"apple"的索引。

我有这个,但我不明白yield

def myIndexOf(list)  
  yield answer if block_given?  
  result = list.index(answer)  
  return answer  
end  

任何人都可以对此有所了解吗?

3 个答案:

答案 0 :(得分:7)

了解yield / blocks实际上非常简单。只需将块视为方法,将yield视为调用这些方法的方法。

想象一下,你有这个

而不是阻止
def is_this_the_right_item?(item)
  item == "apple"
end

def myIndexOf(a_list)
  # your implementation goes here
end

answer = myIndexOf(list)

您可以对myIndexOf实施进行编码吗?它根本不涉及屈服。当您完成后,只需将该块恢复为myIndexOf的调用,并将is_this_the_right_item?的所有来电替换为yield

答案 1 :(得分:1)

yield调用该块。

以下功能是"相同"

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

两者都可以称为

example { |each| puts each }
然后

两者都将输出

1
2
3

希望有助于揭示Ruby中的高阶函数。

答案 2 :(得分:0)

继Sergio的回答:

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

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

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

我正在提交,因为我觉得这是一个棘手的练习和逆向工程,答案可能对你有帮助。

相关问题