【问题标题】:Instantiating instance variable as block将实例变量实例化为块
【发布时间】:2015-04-26 12:37:55
【问题描述】:

我有以下课程

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

【问题讨论】:

    标签: ruby


    【解决方案1】:

    您的方法调用语法不正确。

    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 中的工作原理。

    【讨论】:

      【解决方案2】:

      我在您的代码中发现了不同的错误。修正后,可以应用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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-14
        • 2014-10-05
        • 1970-01-01
        • 1970-01-01
        • 2021-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多