Doing math in Ruby

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:

puts “Enter Equation”
answervar = gets.chomp
doneans = answervar.to_i
puts doneans

Yet, all that did was return the first number of the equation. Any help
or advice would be greatly appreciated. Thanks!

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.

This is not simple. Try simpler.

Blog: http://random8.zenunit.com/
Twitter: http://twitter.com/random8r
Learn: http://sensei.zenunit.com/
New video up now at http://sensei.zenunit.com/
real fastcgi rails deploy process! Check it out now!

On Thu, Sep 6, 2012 at 8:52 PM, Jon M. [email protected] wrote:

puts doneans

Yet, all that did was return the first number of the equation. Any help
or advice would be greatly appreciated. Thanks!


Posted via http://www.ruby-forum.com/.

If it’s just a tool for you to use, then I’d just eval the inputs (does
constrain the syntax a bit, though)

If you want to take in user input, then you’ll need to do some kind of
parsing of the input. A quick search found
Math Parser, Part 4: Tests - Lukasz Wrobel which looks pretty
simple, but might work. Otherwise, try searching through rubygems.org
and
ruby-toolbox.com