Calculate input - numbers

Hi

user_input = $stdin.gets.chomp

Now the user types:

“5 + 5”

As string (without the quotes).

user_input is now a string object containing “5 + 5”

I would like to give back the result of the operation, which should be
10.

Right now I use eval() and it works, but I am wondering if there is a
better alternative for it? How does IRB solve this?

On Sat, Jul 27, 2013 at 1:44 PM, Marc H. [email protected]
wrote:

user_input is now a string object containing “5 + 5”

I would like to give back the result of the operation, which should be
10.

Right now I use eval() and it works, but I am wondering if there is a
better alternative for it? How does IRB solve this?

IRB uses eval too. You can see it here:

https://github.com/ruby/ruby/blob/trunk/lib/irb/workspace.rb#L85

Jesus.

On Sat, Jul 27, 2013 at 1:44 PM, Marc H. [email protected]
wrote:

user_input is now a string object containing “5 + 5”

I would like to give back the result of the operation, which should be
10.

Right now I use eval() and it works, but I am wondering if there is a
better alternative for it? How does IRB solve this?

It probably also uses eval. In your case it’s a security risk because
someone can enter “system(‘rm’, ‘-rf’, ‘$HOME’)” and you’ll see what
happens with that in eval.

The proper way is to use a parser for mathematical expressions. That
would
verify that the expression is OK and you could also use the AST to
evaluate
it. In Ruby you might actually be able to write such a parser with an
arcane regular expression because Ruby’s Oniguruma is capable of
matching
non regular languages (i.e. nested structures with matching brackets).
But
that’ll look horrible, I guess. :slight_smile:

Cheers

robert

On Saturday, July 27, 2013, Marc H. wrote:

Right now I use eval() and it works, but I am wondering if there is a
better alternative for it?

Depends what you mean by “better”. As others have shown, there are
certainly more /secure/ ways, and ways that are much more able to handle
things other than Ruby (i.e., you can make a parser to parse pretty much
anything).

On things that you know to be simple non-dangerous Ruby code, sure, eval
wins /if/ your criterion is ease of use (and you’re already in IRB).
For
most other purposes, yes, there’s some thing better, but which way is
best,
depends on what you want out of it.

-Dave

Am 27.07.2013 14:00, schrieb Robert K.:

It probably also uses eval. In your case it’s a security risk because
someone can enter “system(‘rm’, ‘-rf’, ‘$HOME’)” and you’ll see what
happens with that in eval.

Don’t try that at home, kids! :slight_smile:

On Jul 27, 2013, at 9:08 AM, [email protected] wrote:

Am 27.07.2013 14:00, schrieb Robert K.:

It probably also uses eval. In your case it’s a security risk because
someone can enter “system(‘rm’, ‘-rf’, ‘$HOME’)” and you’ll see what
happens with that in eval.

Don’t try that at home, kids! :slight_smile:

We’re all professionals here. :slight_smile: