CSC/ECE 517 Summer 2008/wiki1 7 n1: Difference between revisions
Jump to navigation
Jump to search
mNo edit summary |
No edit summary |
||
Line 1: | Line 1: | ||
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. | ''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 | |||
===Module.class_eval=== |
Revision as of 21:43, 6 June 2008
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