יום רביעי, 21 במאי 2014

Ruby define_method simple sample‏

The following Ruby code demonstrates the use of rubies define_method in order to define methods dynamically.

class MyCls
      %w(getData1 getData2).each do |meth|
      define_method(meth) {
        @data[meth.to_sym] = @data[:User] * 2
        @data[meth.to_sym]
        }
  def initialize()
    @data = {}
    @data[:User]= 15 
    end
  end
end
theMyCls = MyCls.new()
puts  theMyCls.getData2
 

Resources
#http://ruby-doc.org/core-2.0/Module.html#method-i-define_method
#http://www.trottercashion.com/2011/02/08/rubys-define_method-method_missing-and-instance_eval.html

אין תגובות:

הוסף רשומת תגובה