Class: FreeStruct
Overview
Convert hash to object with methods
o = FreeStruct.new name: 'a'
o.name -> 'a'
o[:name] -> 'a'
o.name = 'b'
o.name 'b'
o.name -> 'b'
o.name = nil
o.name -> nil
o.title -> raises error
Instance Method Summary collapse
- #[](key) ⇒ Object
-
#initialize(hash) ⇒ FreeStruct
constructor
A new instance of FreeStruct.
- #to_h ⇒ Object
Constructor Details
#initialize(hash) ⇒ FreeStruct
Returns a new instance of FreeStruct.
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/common/free_struct.rb', line 13 def initialize hash @keys = hash.keys hash.each do |key, value| ivar = "@#{key}" instance_variable_set ivar, value define_singleton_method(key) do instance_variable_get ivar end define_singleton_method "#{key}=" do |val| instance_variable_set ivar, val end end end |