CSC/ECE 517 Summer 2008/wiki1 7 n1
Ruby's eval can parse and execute an arbitrary string of Ruby code. Does Java have a similar facility? Provide an illustration of what this facility is good for. Compare the ease of writing such code in Ruby vs. writing equivalent code in Java.
Evaluation Options in Ruby
The eval method is one of the most powerful features of Ruby. The Kernel.eval will parse and execute an arbitrary string of legal Ruby source code. To put it plainly, if your Ruby program can generate a string of valid Ruby code, the Kernel.eval method can evaluate that code. This facility gives developers the ability to modify the runtime behavior of application.
Using eval method is straightforward in Ruby.
Kernel.eval
eval("puts \"Hello World\"") #--> Hello World
Kernel.eval with Kernel#binding
def get_binding
a = 1
binding
end
a = 2
the_binding = get_binding
eval("puts a", the_binding) #--> 1
eval("puts a") #--> 2
Object.instance_eval
class Paginator
def initialize
@page_index = 0
end
def next
@page_index += 1
end
end
paginator = Paginator.new
paginator.next
paginator.instance_eval("puts @page_index") #=> 1