DEV Community

loading...

Check your Ruby Developer Level with simple task

decentralizuj profile image decentralizuj ・2 min read

I just found an old post from @evanilukhin showing interview task - Simple word calculator. I was reading it on my mobile, so first I read his post, and decided to not look at the answer code (anyway it's impossible to understand on small android display).

Task is next: make this code work:

one.plus.two.equal    # =>  3
one.minus.three.equal # => -2
Enter fullscreen mode Exit fullscreen mode

While you're on interview, it can be harder than it should be. Few minutes later electricity came back (some works during this morning... awful), so I decided to try to solve it (in his post I read it's good for every developer to check his skills... and it's true). You have a link to his post if you want to read it and see his results (probably better than mine, but hey, 10 minutes on android 5, and it works... :P).

So what do you think, are you able to make this code work without reading the rest? Here's my solution (first one, fast one):

My Answer
  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

and about 10 minutes later I decided to make this more DRY, and to allow it to use 'one' chained more times (like original article code work)

  class One
    def initialize
      @num = 1
    end

    def one
      use_number 1
    end

    def two
      use_number 2
    end

    def three
      use_number 3
    end

    def plus;  set_opt(:add) end
    def minus; set_opt(:rmw) end

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

    private

    def set_opt(opt)
      @opt = opt; return self
    end

    def use_number(number)
      case @opt
        when :add then @num += number.to_i
        when :rmw then @num -= number.to_i
        else @num
      end
      @opt = nil
      return self
    end
  end

one = One.new
one.plus.two.equal # => 3
one.plus.two.minus.three.plus.one.equal => 1
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide