jumpstart 2 assessment 2 calculator
Calculator
You are given a hash with letters as keys and mathematical operators as values, an input array of numbers and letters, and a starting value.
Write a method that goes takes the start value then goes through the input array performing the operation on the accumulated output and up until that point and the next number in the array. If a letter in the input does not appear in the hash, skip it and the number after it.
Example:
hash = {"a" => "+", "z" => "*", "t" => "/"}
input = ["z", 5, "t", 8]
start = 9
calculater(hash, input, start) = 5 (remember integer division!)
Hard coded solution:
def calculater(hash, input, start)
count = 0
while count < input.length
if hash[input[count]] == "+"
start = start + input[count+1]
elsif hash[input[count]] == "*"
start = start * input[count+1]
elsif hash[input[count]] == "/"
start = start / input[count+1]
elsif hash[input[count]] == "-"
start = start - input[count+1]
end
count += 1
end
start
endUsing a newly learned method, send:
def calculater(hash, input, start)
(1..input.length).step(2) do |index|
if hash.key?(input[index - 1])
start = start.send(hash[input[index - 1]], input[index])
end
end
start
endThese are the corresponding test cases that must pass as true:
puts "---------Calculater---------"
hash = {"a" => "+", "z" => "*", "t" => "/"}
hash2 = { "y" => "*", "r" => "/", "u" => "-"}
puts calculater(hash, ["z", 5, "t", 8], 9) == 5
puts calculater(hash, ["z", 5, "z", 3], 3) == 45
puts calculater(hash2, ["a", 5, "y", 7, "r", 9, "u", 4], 8) == 2
puts calculater(hash2, ["y", 5, "u", 20, "r", 9, "y", 4], 0) == -12