Hello everybody. I am new to Ruby and understand the bare minimum of
basic concepts. I was wondering if there was a way to take the input of
a user (supposedly a mathematical equation) and return the answer. For
example, if I started the Ruby script in my Terminal, is there a way
that I would be able to type in 1+2 and get a returned answer of 3?
Something I tried was:
Yet, all that did was return the first number of the equation.
===
to_i(base=10) → integer
Returns the result of interpreting leading characters in str as an
integer base base (between 2 and 36). Extraneous characters past the end
of a valid number are ignored. If there is not a valid number at the
start of str, 0 is returned.
puts “1abc”.to_i
puts “abc1”.to_i
–output:–
1
0
You can do this:
result = eval “1+2”
puts result
–output:–
3
But if someone input some malicious ruby statements, and you eval them,
you could erase
your whole hard drive.
So what you are trying to do is more complicated. You have to examine
each character in the string and try to decide what it is: a number or
an
operator.