Skip to content

Instantly share code, notes, and snippets.

@adhithyan15
Created June 15, 2013 04:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adhithyan15/5786879 to your computer and use it in GitHub Desktop.
Save adhithyan15/5786879 to your computer and use it in GitHub Desktop.
A simple command line calculator using Slop to process command line arguments. Licensed under MIT.
require 'slop'
# add(5,6,13) => 24
def add(list_of_integers)
result = 0
list_of_integers.each do |num|
result = result + num
end
return result
end
# subtract(5,6) => -1
def subtract(list_of_integers)
number1 = list_of_integers[0]
number2 = list_of_integers[1]
number1-number2
end
# multiply(6,7) => 42
def multiply(list_of_integers)
result = 1
list_of_integers.each do |num|
result = result*num
end
return result
end
# divide(42,6) => 7
def divide(list_of_integers)
number1 = list_of_integers[0]
number2 = list_of_integers[1]
number1/number2
end
opts = Slop.parse do
on :a, :add=, 'Addition', as: Array
on :s, :subtract=, 'Subtraction', as: Array
on :m, :multiply=, 'Multiplication', as: Array
on :d, :divide=, 'Division', as: Array
end
opts = opts.to_hash
if opts[:add] != nil
puts add(opts[:add].collect{|element| element.to_i})
elsif opts[:subtract] != nil
puts subtract(opts[:subtract].collect{|element| element.to_i})
elsif opts[:multiply] != nil
puts multiply(opts[:multiply].collect{|element| element.to_i})
elsif opts[:divide] != nil
puts divide(opts[:divide].collect{|element| element.to_i})
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment