ruby - Difference between passing arguments to define_method and to the following block? -


i confused following code poignant guide:

# guts of life force within dwemthy's array class creature    # metaclass class   def self.metaclass; class << self; self; end; end    # advanced metaprogramming code nice, clean traits   def self.traits( *arr )     return @traits if arr.empty?      # 1. set accessors each variable     attr_accessor( *arr )      # 2. add new class method each trait.     arr.each |a|       metaclass.instance_eval         define_method( ) |val|           @traits ||= {}           @traits[a] = val         end       end     end      # 3. each monster, `initialize' method     #    should use default number each trait.     class_eval       define_method( :initialize )         self.class.traits.each |k,v|           instance_variable_set("@#{k}", v)         end       end     end    end    # creature attributes read-only   traits :life, :strength, :charisma, :weapon end 

the above code used create new class, in following:

class dragon < creature   life( 1340 )     # tough scales   strength( 451 )  # bristling veins   charisma( 1020 ) # toothy smile   weapon( 939 )    # fire breath end 

i need study basics of meta-programming more on own, want know, val block argument come in define_method( ) |val|? represents point values assigned each trait, don't understand how each of numbers become block argument.

also, why a passed in parentheses define_method, while val passed in block argument?

i've read on this question on subject of define_method arguments, doesn't address reasons passing arguments define_method rather block.

in form

define_method(:foo){|x| ...} 

:foo method name , x argument. have different roles. same as:

def foo(x)   ... end 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -