Ruby 关于 block 的问题

angelfan · February 26, 2015 · Last by angelfan replied at March 07, 2015 · 2203 hits
class Song
  attr_reader :a

  def initialize
    @a = []
  end

  def abc
    @a << 10
  end

end

def song
  sing = Song.new
  yield sing
end

def song(&block)
  sing = Song.new
  capture(sing , &block)
end

song do |a|
  a.abc
  a.abc
  a.abc
end

end

我想问一下的是,yield sing 和 capture(sing , &block) 有什么不同 (ps:我写的是第一种,第二种用 capture(sing , &block) 是我在别的地方看到的,如果因为简化代码造成 capture 用法错误还请指出,见谅哈,因为我从来没用这样用过 capture)

undefined method `capture' for main:Object (NoMethodError)

capture 是啥意思?

items.each { |item| puts item} items.each do |item| puts item end 有啥区别?

#3 楼 @imconfused 两种写法 块内代码很简单 就可以用 items.each { |item| puts item}

You need to Sign in before reply, if you don't have an account, please Sign up first.