You can't use local variables defined outside a method within that method. Instead, you have to pass it as an argument:
def mul(num1, num2)
puts num1 * num2
end
You also don't have to use the same variable names, use whatever makes sense in the context of the method:
def mul(a, b)
puts a * b
end
mul(2, 3)
# prints 6
Methods usually become more versatile if they do one thing. The above implementation multiplies a
and b
and then prints the result via puts
. Let's move the printing outside the method:
def mul(a, b)
a * b
end
puts mul(2, 3)
# prints 6
We can now perform actual calculations:
x = mul(2, 3) #=> 6
y = mul(2, 5) #=> 10
puts mul(x, y)
# prints 60
This wouldn't have been possible with the variant which incorporated puts
.
With user input and output: (using whole numbers for demonstration purposes)
print "first factor: "
num1 = gets.to_i
print "second factor: "
num2 = gets.to_i
puts "#{num1} * #{num2} = #{mul(num1, num2)}"
Note that #{...}
is needed to interpolate other values.
Example session:
first factor: 2
second factor: 3
2 * 3 = 6
To have different output based on a given operator, you need a conditional, e.g. a case
statement:
op = gets.chomp
case op
when 'mul'
puts mul(num1, num2)
when 'add'
puts add(num1, num2)
# ...
end
Hope this will get you started.