Module: KeyDial::Coercion::Hashes::ClassMethods
- Defined in:
- lib/key_dial/coercion.rb
Instance Method Summary collapse
-
#from(obj) ⇒ Object
Allows you to do Hash.from(obj) to create a Hash from any object intelligently.
Instance Method Details
#from(obj) ⇒ Object
Allows you to do Hash.from(obj) to create a Hash from any object intelligently.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/key_dial/coercion.rb', line 38 def from(obj) case obj when Hash return obj when Array # Hash from Array. Forgiving and avoids errors. ['a', 'b', 'c'] will become {0 => 'a', 1 => 'b', 2 => 'c'} obj.each_with_index.map { |k, i| if k.is_a?(Array) if k.empty? [i, nil] elsif k.size == 2 k # k in this case is a keyval pair, e.g. [k, v] else [i, k] end else [i, k] end }.to_h when Struct # Hash from Struct return obj.to_h else {0 => obj} end end |