Ruby/Development/eval

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Add a new method with eval

class String
  eval %{def last(n)
           self[-n, n]
         end}
end
"Here"s a string.".last(7)               # => "string."



Evaluation with variable

x = 1
eval "x + 1"  # => 2



eval with variable name

x = 1
varname = "x"
eval(varname)           # => 1
eval("varname = "$g"")  # Set varname to "$g"
eval("#{varname} = x")  # Set $g to 1
eval(varname)           # => 1



Execute an eval in a thread

def safe_eval(str)
  Thread.start {            # Start sandbox thread
    $SAFE = 4               # Upgrade safe level
    eval(str)               # Eval in the sandbox
  }.value                   # Retrieve result
end



Use eval to run a statement dynamically

#!/usr/bin/env ruby
eval "puts "Hello, myValue!"" # => Hello, myValue!