2015-02-24 172 views
1

我有下面的類實例化實例變量爲塊

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

您的方法調用語法不正確。

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

我看到你的代碼不同的錯誤。糾正後,您可以申請lambda

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

一些鏈接,可以幫助理解發生了什麼:

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

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

並通過調用它

  1. Lambdas
  2. Classes
  3. Lambdas 2