HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Simple calculator using eval

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
evalsimplecalculatorusing

Problem

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

Solution

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.

Context

StackExchange Code Review Q#80699, answer score: 4

Revisions (0)

No revisions yet.