Hey, I’m new to the forum and I’ve just learned Ruby. I’ve been trying
to make a calculator and its giving me an argumenterror (def add) and
querying my ‘if’ statements. Here is my code:
puts “Input first number.”
y = gets.chomp
puts “Input second number.”
x = gets.chomp
puts “What is your function? (add,subtract,multiply,divide)”
z = gets.chomp.downcase
def add(y, x)
y + x+
end
def subtract(y, x)
y - x
end
def divide(y, x)
y / x
end
def muliply(y, x)
y * x
end
There’s a bunch of things wrong, and you might be able to figure them
out, using the error messages that Ruby will give you.
You have a “+” too many in you “add” method, and you aren’t calling your
methods with parameters in you if-else. You are trying to call e.g.
“add” instead of comparing with the string “add”. You are also not doing
operations on numbers, but rather on string. This can be mended by
calling “to_f” on the number from input.
Here’s a working version:
puts “Input first number.”
y = gets.chomp.to_f
puts “Input second number.”
x = gets.chomp.to_f
puts “What is your function? (add,subtract,multiply,divide)”
z = gets.chomp.downcase
def add(y, x)
y + x
end
def subtract(y, x)
y - x
end
def divide(y, x)
y / x
end
def muliply(y, x)
y * x
end
puts case z
when “add”
add(y, x)
when “subtract”
subtract(y, x)
when “multiply”
multiply(y, x)
when “divide”
divide(y, x)
else
“Function not valid.”
end
Nice. Okay, so let’s say I was satisfied with the code and I wanted to
turn it into an exe. file. What would be my next step?
Then I suggest you find another programming language.
Ruby is an interpreted language. This means that you have an
interpreter, ruby, which reads the source-file line by line and executes
it. It doesn’t get compiled into a binary first, like you’d see with a
compiled language, like C, Java or Haskell.
This of course means that the receiving end has to have the interpreter,
and more so, the same version of the interpreter (most are backwards
compatible, but we did introduce a new hash syntax back in 1.9)