Ruby Basics: Block

An example use of block to implement a Calculator:

# Usage: 3*2-1
#
# Calculator.run do |calculator|
#   calculator.add 3
#   calculator.multiply 2
#   calculator.substract 1
# end
# => 5
class Calculator
  def self.run(init: 0)
    yield Operations.new(init)
  end
end

class Operations
  def initialize(init = 0)
    @init = init
  end

  def add(value)
    self.init += value
  end

  def substract(value)
    self.init -= value
  end

  def multiply(value)
    self.init = init * value
  end

  def divide(value)
    self.init = init / value.to_f
  end

  def clear
    self.init = 0
  end

  private
  attr_accessor :init
end