Module: Gorillib::Hashlike::EnumerateFromKeys
- Defined in:
- lib/gorillib/hashlike.rb
Overview
Provides a natural default iteration behavior by iterating over #keys. Since most classes will want this behaviour, it is included by default unless the class has already defined an #each method.
Classes that wish to define their own iteration behavior (Struct for example, or a database facade) must define all of the methods within this module.
Instance Method Summary collapse
-
#each(&block) ⇒ Object
Calls +block+ once for each key in +hsh+, passing the key/value pair as parameters.
-
#each_pair ⇒ Object
Calls +block+ once for each key in +hsh+, passing the key/value pair as parameters.
-
#length ⇒ Fixnum
Returns the number of key/value pairs in the hashlike.
-
#values ⇒ Array
A new array populated with the values from +hsh+.
-
#values_at(*allowed_keys) ⇒ Array
Array containing the values associated with the given keys.
Instance Method Details
#hsh.each {|key, val| ... } ⇒ Hashlike #hsh.each(->an_enumerator) ⇒ Enumerator
Calls +block+ once for each key in +hsh+, passing the key/value pair as parameters.
If no block is given, an enumerator is returned instead.
153 154 155 156 |
# File 'lib/gorillib/hashlike.rb', line 153 def each(&block) return enum_for(:each) unless block_given? each_pair(&block) end |
#hsh.each_pair {|key, val| ... } ⇒ Hashlike #hsh.each_pair(->an_enumerator) ⇒ Enumerator
Calls +block+ once for each key in +hsh+, passing the key/value pair as parameters.
If no block is given, an enumerator is returned instead.
113 114 115 116 117 118 119 |
# File 'lib/gorillib/hashlike.rb', line 113 def each_pair return enum_for(:each_pair) unless block_given? keys.each do |key| yield([key, self[key]]) end self end |
#length ⇒ Fixnum
Returns the number of key/value pairs in the hashlike.
169 170 171 |
# File 'lib/gorillib/hashlike.rb', line 169 def length keys.length end |
#values ⇒ Array
A new array populated with the values from +hsh+.
184 185 186 |
# File 'lib/gorillib/hashlike.rb', line 184 def values [].tap{|arr| each_pair{|key, val| arr << val } } end |
#values_at(*allowed_keys) ⇒ Array
Array containing the values associated with the given keys.
205 206 207 208 209 210 |
# File 'lib/gorillib/hashlike.rb', line 205 def values_at(*allowed_keys) allowed_keys.map do |key| key = convert_key(key) if respond_to?(:convert_key) self[key] if has_key?(key) end end |