Module: KeyDial::Coercion::Arrays
- Included in:
- Array
- Defined in:
- lib/key_dial/coercion.rb
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
-
#to_hash ⇒ Object
Convert an Array to a Hash, providing an alternative to the native to_h() method.
-
#to_struct(type_class = nil) ⇒ Object
Convert an Array to a Struct.
Class Method Details
.included(base) ⇒ Object
60 61 62 |
# File 'lib/key_dial/coercion.rb', line 60 def self.included(base) base.extend ClassMethods end |
Instance Method Details
#to_hash ⇒ Object
Convert an Array to a Hash, providing an alternative to the native to_h() method. to_hash() is more forgiving and avoids errors. [‘a’, ‘b’, ‘c’] will become => ‘a’, 1 => ‘b’, 2 => ‘c’
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/key_dial/coercion.rb', line 36 def to_hash self.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 end |
#to_struct(type_class = nil) ⇒ Object
Convert an Array to a Struct. [‘a’, ‘b’, ‘c’] will become <Struct :‘0’=‘a’, :‘1’=‘b’, :‘2’=‘c’>
56 57 58 |
# File 'lib/key_dial/coercion.rb', line 56 def to_struct(type_class = nil) return Coercion::Structs.create(self, type_class) end |