CSC/ECE 517 Summer 2008/wiki1 7 ev

From Expertiza_Wiki
Jump to navigation Jump to search

Section

Eval

  • A

Ruby

The eval function can be used for dynamically calling functions. For example in Ruby:

  # Create an array of functions
  functions = ['function1','function2','function3']
  
  # Define functions
  def function1()
      puts "inside function1"
  end 

  def function2()
     puts "inside function2"
  end 

  def function3()
     puts "inside function3"
  end 

  # Factory Pattern
  def CallFunction(functionname)
     eval functionname
  end 

  #Results
  irb(main):039:0> CallFunction functions[0]
  inside function1
  => nil
  irb(main):040:0> CallFunction functions[1]
  inside function2
  => nil
  irb(main):041:0> CallFunction functions[2]
  inside function3
  => nil

What makes this so powerful is that the function names in the array can be stored in an array or someplace else like a database or xml file.

Taking this one step further we can store the function definition in an array as well:

  #Create an array for the function name and function definition
  function1 = ['function4'] # We could have more then one
  function2 =['def function4 ()  puts "inside function4" end'] # We could have more then one
  
  # Dynamically create/define function
  eval function2[0]
  
  # Dynamically call the the name of the function
  irb(main):060:0> eval function1[0]
  inside function4
  => nil

So, in this example function4() is created dynamically at run-time. This allows us to store parts of the code as data and to create functions when needed. An application written using eval to dynamically generate functions would allow new functions to be added easily. For example, you could create new definitions of functions and insert them into a database table.

Java

  1. a
    1. b

Subsubsection


Back to the assignment page