DEV Community

Discussion on: Can you…? - Calculator

Collapse
 
ben profile image
Ben Halpern

Too lazy to figure out how to deal with the remainder in division, but here is a cut at a calculator in Ruby that doesn't use math operators.

def add(num_1, num_2)
  [num_1, num_2].sum
end

def multiply(num_1, num_2)
  arr = []
  num_1.times do |n|
    arr << num_2
  end
  arr.sum
end

def subtract(num_1, num_2)
  subtractable = num_2.positive? ? "-#{num_2}".to_i : num_2.to_s.gsub("-", "").to_i
  [num_1, subtractable].sum
end

def divide(num_1, num_2)
  arr = []
  while num_1 >= num_2
    arr << "whatever"
    num_1 = subtract(num_1, num_2)
  end
  arr.size
end
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vulcanwm profile image
Medea

Wow .sum is a function in Ruby? That made it so easy.

Collapse
 
ben profile image
Ben Halpern

Yeah, that's sort of a cheat — but Ruby's like that 🤣

eval("10 + 10") also would have been a quick answer here, but that seemed just a bit too easy.

Thread Thread
 
vulcanwm profile image
Medea • Edited

Oh- wow