4
\$\begingroup\$

The following code is for a calculator made in ruby, I find that this way saves much time than having to build this calculator from scratch, especially that I want it to support BEMDAS operations. However, I'm feeling that it is inefficient because I'm using eval, and I think this could be dangerous. Is it a good idea to use this in a real life application?

include Math
puts "enter an expression:"
input =  gets.chomp
begin
    result = eval(input)
    if (result.is_a? Numeric)
        puts result
    else
        puts "syntax error"
    end
rescue Exception
end
\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

eval is much too powerful for a calculator. If there is any chance at all that the program will be used by a hostile user, then you must not use eval. Your program allows the user to execute any Ruby code that can fit on one line.

Furthermore, any attempt to sandbox eval in Ruby would be hopeless. Consider that numbers are objects that have powerful methods. Try entering this as input:

3.send(:eval, "File.delete('/tmp/dummy.txt')")

That would delete the file /tmp/dummy.txt if the user has the filesystem permissions to do so.

\$\endgroup\$
4
\$\begingroup\$

I do not know Ruby, but from my Python knowledge, it is not good to use eval in a real program. When you use eval, it executes the code directly, so accidental/experimental input can have unwanted results, or even destroy the system. Also, this has the potential for a hacker who has limited access to the system to run this program and do whatever they want as long as they have access to it, instead of cracking in deeper and doing whatever they are trying to do.

See this question for a detail discussion about eval in Ruby.

This question is about python, but also has good points.

\$\endgroup\$
3
  • \$\begingroup\$ Why do they make eval so strong? Why not just make it evaluate a mathematical expression? That's what it's going to be used for in most cases anyways, right? \$\endgroup\$ Commented Feb 16, 2015 at 23:39
  • 1
    \$\begingroup\$ I don't know, I don't know, and I don't know. \$\endgroup\$ Commented Feb 17, 2015 at 0:02
  • \$\begingroup\$ @BWG because the language designers who think eval is a good thing are idiots. Almost every scripting language supports eval and people use it, so why not implement it? \$\endgroup\$ Commented Feb 17, 2015 at 1:45

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.