DEV Community

Discussion on: Ruby Interview Tasks - Simple word calculator

Collapse
decentralizuj profile image
decentralizuj • Edited on

Just to add approach that I wrote before reading your answers (your is better, but, well, it was just for fun :)

  class One
    def initialize
      @num = 1
    end

    def plus
      @opt = :add
      return self
    end

    def minus
      @opt = :rmw
      return self
    end

    def two
      case @opt
        when :add then @num += 2
        when :rmw then @num -= 2
      end
      return self
    end

    def three
      case @opt
        when :add then @num += 3
        when :rmw then @num -= 3
      end
      return self
    end

    def equal
      num  = @num
      @num = 1
      return num
    end
  end

  one = One.new
  one.plus.two.equal    =>  3
  one.minus.three.equal => -2
Enter fullscreen mode Exit fullscreen mode
Collapse
evanilukhin profile image
Ivan Ilyukhin Author

That's why I love Ruby! It allows you to solve a problem in a large number of ways.