Class: Hash::Sorted
- Inherits:
-
Object
- Object
- Hash::Sorted
- Extended by:
- Forwardable
- Includes:
- Enumerable
- Defined in:
- lib/hash_ext/sorted.rb
Class Method Summary collapse
- .ascending(hash = {}, &sort_criteria) ⇒ Object (also: asc)
- .descending(hash = {}, &sort_criteria) ⇒ Object (also: desc)
Instance Method Summary collapse
- #each ⇒ Object (also: #each_pair)
- #each_key ⇒ Object
- #each_value ⇒ Object
-
#initialize(hash = {}, direction = :asc, &sort_criteria) ⇒ Sorted
constructor
A new instance of Sorted.
- #keys ⇒ Object
- #to_h ⇒ Object
- #values ⇒ Object
Constructor Details
#initialize(hash = {}, direction = :asc, &sort_criteria) ⇒ Sorted
Returns a new instance of Sorted.
18 19 20 21 22 |
# File 'lib/hash_ext/sorted.rb', line 18 def initialize(hash={}, direction=:asc, &sort_criteria) @hash = hash @direction = direction @sort_criteria = sort_criteria end |
Class Method Details
.ascending(hash = {}, &sort_criteria) ⇒ Object Also known as: asc
59 60 61 |
# File 'lib/hash_ext/sorted.rb', line 59 def ascending(hash={}, &sort_criteria) new hash, :asc, &sort_criteria end |
.descending(hash = {}, &sort_criteria) ⇒ Object Also known as: desc
64 65 66 |
# File 'lib/hash_ext/sorted.rb', line 64 def descending(hash={}, &sort_criteria) new hash, :desc, &sort_criteria end |
Instance Method Details
#each ⇒ Object Also known as: each_pair
33 34 35 36 |
# File 'lib/hash_ext/sorted.rb', line 33 def each return enum_for(:each) unless block_given? keys.each { |k| yield k, self[k]} end |
#each_key ⇒ Object
39 40 41 42 |
# File 'lib/hash_ext/sorted.rb', line 39 def each_key return enum_for(:each_key) unless block_given? keys.each { |k| yield k } end |
#each_value ⇒ Object
44 45 46 47 |
# File 'lib/hash_ext/sorted.rb', line 44 def each_value return enum_for(:each_value) unless block_given? keys.each { |k| yield self[k] } end |
#keys ⇒ Object
24 25 26 27 |
# File 'lib/hash_ext/sorted.rb', line 24 def keys sorted_keys = @hash.sort_by(&sort_criteria).map { |k,v| k } direction == :asc ? sorted_keys : sorted_keys.reverse end |
#to_h ⇒ Object
49 50 51 |
# File 'lib/hash_ext/sorted.rb', line 49 def to_h each_with_object({}) { |(k,v),h| h[k] = v } end |
#values ⇒ Object
29 30 31 |
# File 'lib/hash_ext/sorted.rb', line 29 def values keys.map { |k| self[k] } end |