Well, there's a few things going on here.
First, your function definition:
def calc(a=number, b=operator, c=number, d=operator, e=number)
This should probably be def calc(a=nil, b=nil, c=nil, d=nil, e=nil)
I understand that the example is telling me, the user, that a
should be a number, b
should be an operator, etc, but when you actually define a function that way, what you are doing is setting default values for the parameters. When you use 'number' and 'operator' in the definition, these have no value and end up assigning nil as default. The end result is the same, but it's confusing to anyone reading the code.
Next, I understand what you are trying to do with a,b,c,d,e = gets()
.
If you just run
a,b,c,d,e = 1,2,3,4,5
puts a,b,c,d,e #=>
1
2
3
4
5
Makes sense. However, when you run a Ruby script and use gets()
, then everything that is input at the command line is received as a single string. Therefore when a,b,c,d,e = gets()
is executed, the user input of "1+3" is taken as a string and assigned to a
.
b
, c
, d
, and e
are nil
You then call calc("1+3",nil,nil,nil,nil)
.
calc
then evaluates its one line method definition like so:
puts "Answer: #{"1+3"} #{nil} #{nil} #{nil} #{nil}"
And that's why you just see "Answer: 1+3" as the output.
So, why does it work if you hard code a,b,c,d,e=2*7+1
?
When that line is evaluated, 2*7+1
is evaluated first (15). 15 is then assigned to a
and all the other variables are nil
, like before. Then calc
just prints out the value of a
, which is 15.
So....Let's look at how to make the example work as you expect.
First, I'm going to ignore the menu
method since it's not actually used anywhere in the example.
#!/bin/ruby
def calc(user_input)
result = eval(input_string)
puts "Answer: #{result}"
end
puts "Enter formula"
user_input = gets()
# e.g. "1+3*8"
calc(user_input)
All I'm doing is eval
uating the entered string. Be very careful with eval
. I would never actually use it in this case since a user could enter any kind of ruby script and your program would just run it. Here is an SO question that demonstrates how to implement checks before evaluating the formula.