Runtime evaluation: Difference between revisions

add Ruby
(add Ruby)
Line 185:
'''
10</lang>
 
=={{header|Ruby}}==
 
The <tt>eval</tt> method evaluates a string as code and returns the resulting object. With one argument, it evaluates in the current context:
<lang ruby>a, b = 5, -7
ans = eval "(a * b).abs" # => 35</lang>
 
With two arguments, <tt>eval</tt> runs in the given <tt>Binding</tt> or <tt>Proc</tt> context:
<lang ruby>def first(main_var, main_binding)
foo = 42
second [[main_var, main_binding], ["foo", binding]]
end
 
def second(args)
sqr = lambda {|x| x**2}
deref(args << ["sqr", binding])
end
 
def deref(stuff)
stuff.each do |varname, context|
puts "value of #{varname} is #{eval varname, context}"
end
end
 
hello = "world"
first "hello", binding</lang>
<pre>value of hello is world
value of foo is 42
value of sqr is #<Proc:0x1002ef6c@eval.rb:7></pre>
 
=={{header|Scheme}}==
Anonymous user