ostruct

~/rubytesting/TheRubyProgrammingLanguage/chapter8ReflectionandMetaprogramming$ cat -n ostruct.rb 
     1  require 'ostruct'
     2  
     3  alu = OpenStruct.new
     4  alu.nombre = "Jose"
     5  alu.apellidos = "Rodriguez Quintero"
     6  alu.edad = 97
     7  alu.calificacion = 10
     8  
     9  puts alu

~/rubytesting/TheRubyProgrammingLanguage/chapter8ReflectionandMetaprogramming$ ruby ostruct.rb 
#<OpenStruct nombre="Jose", apellidos="Rodriguez Quintero", edad=97, calificacion=10>

~/rubytesting/TheRubyProgrammingLanguage/chapter8ReflectionandMetaprogramming$ cat -n my_ostruct.rb 
     1  class MyOpenStruct
     2    def initialize(h = {})
     3      @attrs = h
     4    end
     5  
     6    def method_missing(name, *args)
     7      attr = name.to_s
     8      if attr =~ /=$/
     9        @attrs[attr.chop] = args[0]
    10      else
    11        @attrs[attr]
    12      end
    13    end
    14  
    15    def to_s
    16      self.inspect
    17    end
    18  end
    19  
    20  alu = MyOpenStruct.new
    21  alu.nombre = "Jose"
    22  alu.apellidos = "Rodriguez Quintero"
    23  alu.edad = 97
    24  alu.calificacion =  10
    25  
    26  puts alu.nombre
    27  puts alu.edad
    28  puts alu.calificacion
    29  puts alu

~/rubytesting/TheRubyProgrammingLanguage/chapter8ReflectionandMetaprogramming$ ruby my_ostruct.rb 
Jose
97
10
#<MyOpenStruct:0x10016a408 @attrs={"nombre"=>"Jose", "calificacion"=>10, "edad"=>97, "apellidos"=>"Rodriguez Quintero"}>



Casiano Rodriguez León 2015-06-18