实例化实例变量为块
问题描述:
我有下面的类实例化实例变量为块
class Increasable
def initializer(start, &increaser)
@value = start
@increaser = increaser
end
def increase()
value = increaser.call(value)
end
end
如何用块初始化?这样做
inc = Increasable.new(1, { |val| 2 + val})
在irb
我得到
(irb):20: syntax error, unexpected '}', expecting end-of-input
inc = Increasable.new(1, { |val| 2 + val})
答
您的方法调用语法不正确。
class Increasable
attr_reader :value, :increaser
def initialize(start, &increaser)
@value = start
@increaser = increaser
end
def increase
@value = increaser.call(value)
end
end
Increasable.new(1) { |val| 2 + val }.increase # => 3
读Best explanation of Ruby blocks?知道块在Ruby中是如何工作的。