Ruby 请教一个关于 yield 的问题

shangrenzhidao · 2014年09月26日 · 最后由 AaronCui 回复于 2018年06月27日 · 1621 次阅读
class VowelFinder
  include Enumerable

  def initialize(string)
    @string = string
  end
  def each
    @string.scan(/[aeiou]/) do |vowel|
      yield vowel
    end
  end
end

请问 yield 在块中使用,并且加了参数是怎么个情况?

就是将 scan 得到的字符传递给 each 方法后带的代码块中

word = VowelFinder.new "abce"
word.each { |vowel| puts "hello" + vowel }
# outputs
# helloa
# helloe

#1 楼 @costy_peak yield vowel 这就代码的做了什么

#3 楼 @shangrenzhidao 看 2 楼的回复,并且在 irb 里面运行一下,你就知道了

#4 楼 @costy_peak #2 楼 @serco 传给与方法相关联的 block

#5 楼 @shangrenzhidao 看来你已经明白了!翻一下镐头书,里面有相关说明的。。have fun and enjoy!!

#6 楼 @costy_peak 谢谢,刚看到第六章,这书得多琢磨几遍

哇·· 一看帖子好久远了· 不过看了这个帖子· 把块弄明白了·还是谢谢

需要 登录 后方可回复, 如果你还没有账号请 注册新账号