将实例变量实例化为块

时间:2015-02-24 18:25:59

标签: ruby

我有以下课程

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})

2 个答案:

答案 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)

我在代码中看到了不同的错误。纠正后,您可以应用 lambdas

class Increasable
  def initialize(start, increaser)
    @value = start
    @increaser = increaser
  end

  def increase()
    @value = @increaser.call(@value)
  end
end

并通过以下方式调用:

inc = Increasable.new(1, ->(val){ 2 + val}) # => 3

有些链接有助于了解会发生什么:

  1. Lambdas
  2. Classes
  3. Lambdas 2