Skip to content

Instantly share code, notes, and snippets.

/ruby.rb Secret

Created November 1, 2016 09:54
Show Gist options
  • Save anonymous/380443582e8c47941bd44939fb9ccf07 to your computer and use it in GitHub Desktop.
Save anonymous/380443582e8c47941bd44939fb9ccf07 to your computer and use it in GitHub Desktop.
def calc numbers, ops
expression = numbers.zip(ops).flatten.compact
# need some bodmas action
while expression.include?(:/)
result = [expression[expression.index(:/) - 1].to_f,expression[expression.index(:/) + 1].to_f].inject :/
expression.delete(expression[expression.index(:/) - 1])
expression.delete(expression[expression.index(:/) + 1])
expression[expression.index(:/)] = result
end
while expression.include?(:*)
result = [expression[expression.index(:*) - 1].to_f,expression[expression.index(:*) + 1].to_f].inject :*
expression.delete(expression[expression.index(:*) - 1])
expression.delete(expression[expression.index(:*) + 1])
expression[expression.index(:*)] = result
end
while expression.include?(:+)
result = [expression[expression.index(:+) - 1].to_f,expression[expression.index(:+) + 1].to_f].inject :+
expression.delete(expression[expression.index(:+) - 1])
expression.delete(expression[expression.index(:+) + 1])
expression[expression.index(:+)] = result
end
while expression.include?(:-)
result = [expression[expression.index(:-) - 1].to_f,expression[expression.index(:-) + 1].to_f].inject :-
expression.delete(expression[expression.index(:-) - 1])
expression.delete(expression[expression.index(:-) + 1])
expression[expression.index(:-)] = result
end
result
end
p calc [1, 2, 3], [:/, :/]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment