Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass variables to eval?

Tags:

ruby

I am trying to pass a variable to a dynamically declared method like:

eval(def test(name)
 puts name
end
test 'joe')

but it does not work.

Is there a way to do this?

like image 710
Nick Avatar asked Jun 08 '10 04:06

Nick


People also ask

Why eval is not recommended?

Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!

What is a safe alternative to using eval ()?

An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().

Is eval a variable?

= is the assignment operator, and val and _val are variables.

Is eval bad JavaScript?

The eval function and its relatives ( Function , setTimeout , and setInterval ) provide access to the JavaScript compiler. This is sometimes useful, but in most cases it indicates the presence of extremely bad coding. The eval function is the most misused feature of JavaScript.


2 Answers

eval expects a string. The following should work fine:

eval "def test(name)
  puts name
end
test 'joe'"
like image 110
Brian McKenna Avatar answered Oct 02 '22 14:10

Brian McKenna


If you want to declare a method dynamically then a better way to do that is to use define_method instead of eval, like so

define_method(:test) do |name|
  name
end

test 'joe'
#=> joe

Don't use eval unless it is absolutely necessary and you are 120% sure that it is safe. Even if you are 120% sure that it is safe, still try to look for other options and if you find one then use that instead of eval.

like image 42
nas Avatar answered Oct 02 '22 16:10

nas