我有以下课程
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})
答案 0 :(得分:2)
您的方法调用语法不正确。
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中工作。
答案 1 :(得分:1)