1

I have the following class

class Increasable

  def initializer(start, &increaser)
    @value = start
    @increaser = increaser
  end

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

How do I initialize with a block? Doing

inc = Increasable.new(1, { |val|  2 + val})

in irb I get

(irb):20: syntax error, unexpected '}', expecting end-of-input
inc = Increasable.new(1, { |val|  2 + val})
Stam180
  • 13
  • 2

2 Answers2

2

Your method calling syntax was incorrect.

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

Read Best explanation of Ruby blocks? to know how blocks work in Ruby.

Community
  • 1
  • 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
1

I see different mistakes in your code. After correcting, you can apply lambdas.

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

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

And call it by:

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

Some links that can help to understand what happens:

  1. Lambdas
  2. Classes
  3. Lambdas 2
Farkhat Mikhalko
  • 3,565
  • 3
  • 23
  • 37