Skip to content

Instantly share code, notes, and snippets.

@juandefelix
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save juandefelix/02f22b8599c0b12c9654 to your computer and use it in GitHub Desktop.

Select an option

Save juandefelix/02f22b8599c0b12c9654 to your computer and use it in GitHub Desktop.

Revisions

  1. juandefelix renamed this gist Jun 5, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. juandefelix renamed this gist Jun 5, 2014. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. juandefelix revised this gist Jun 5, 2014. 1 changed file with 19 additions and 0 deletions.
    19 changes: 19 additions & 0 deletions calculator_spec.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    require 'calculator'

    describe "method calculator exist" do
    it "calculator 2 + 3 == 5" do
    expect(calculator("2 + 3")).to eq 5
    end
    end

    describe "method subtraction" do
    it "10 - 5 == 5" do
    expect(calculator("10 - 5")).to eq(5)
    end
    end

    describe "method with multiple operators" do
    it "10 - 5 == 5" do
    expect(calculator("12 + 1 * 2 + 4 / 2")).to eq(16)
    end
    end
  4. juandefelix created this gist Jun 5, 2014.
    22 changes: 22 additions & 0 deletions calculator.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    def calculator string
    while string.match /[*\/]/
    # p string
    string.gsub!(/(\d+)\s*([*\/])\s*(\d+)/) do |regex|
    num1 = $1.to_i
    num2 = $3.to_i
    operator = $2.to_sym
    "#{[num1, num2].reduce(operator)}"
    end
    end

    while string.match /[-\+]/
    string.gsub!(/(\d+)\s*([-\+])\s*(\d+)/) do |regex|
    num1 = $1.to_i
    num2 = $3.to_i
    operator = $2.to_sym
    "#{[num1, num2].reduce(operator)}"
    end
    end

    string.to_i
    end