我有下列课程
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):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中是如何工作的。
关于ruby - 将实例变量实例化为块,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28703425/