From: Robert Klemme Date: 2013-07-27T21:00:16+09:00 Subject: Re: Calculate input - numbers --047d7bb03e6a8bea1504e27d008d Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable On Sat, Jul 27, 2013 at 1:44 PM, Marc Heiler wrote: > Hi > > user_input =3D $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? > 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=B4, I guess. :-) Cheers robert --=20 remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/ --047d7bb03e6a8bea1504e27d008d Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable



On Sat, Jul 27, 2013 at 1:44 PM, Marc Heiler <= lists@ruby-forum.= com> wrote:
Hi

user_input =3D $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?
It probably also uses eval. In your case it's a security r= isk because someone can enter "system('rm', '-rf', = 9;$HOME')" and you'll see what happens with that in eval.

The proper way is to use a parser for mathematical expr= essions. =A0That would verify that the expression is OK and you could also = use the AST to evaluate it. =A0In Ruby you might actually be able to write = such a parser with an arcane regular expression because Ruby's Onigurum= a is capable of matching non regular languages (i.e. nested structures with= matching brackets). =A0But that'll look horrible=B4, I guess. :-)

Cheers

robert


--
remember.guy do |as, often| as.you_can -= without end
http://blog.= rubybestpractices.com/
--047d7bb03e6a8bea1504e27d008d--