Module: ToHash
- Defined in:
- lib/to_hash.rb
Overview
Generic ToHash mixin
Instance Method Summary collapse
-
#to_hash(*keys) ⇒ Object
to_hash generic implementation, generates a hash from object Mixing in this module from instance variables of the object.
Instance Method Details
#to_hash(*keys) ⇒ Object
to_hash generic implementation, generates a hash from object Mixing in this module from instance variables of the object
Example:
class Foo
include ToHash
def initialize
@a = 1
@b = 2
@c = 3
end
end
Foo.new.to_hash #=> { :a => 1, :b => 2, :c => 3}
Foo.new.to_hash(:c, 'a') #=> { 'a' => 1, :c => 3 }
Arguments:
*keys: (Optional key list)
21 22 23 24 25 26 27 |
# File 'lib/to_hash.rb', line 21 def to_hash(*keys) keys = keys.any? ? __named_map(keys) : __instance_map keys = keys.map do |key, val| [key, instance_variable_get(val)] end Hash[keys] end |