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?
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!
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 the assignment operator, and val and _val are variables.
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.
eval
expects a string. The following should work fine:
eval "def test(name)
puts name
end
test 'joe'"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With