Class: Hash::Sorted

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/hash_ext/sorted.rb

Class Method Summary collapse

Instance Method Summary collapse

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

#eachObject 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_keyObject



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_valueObject



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

#keysObject



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_hObject



49
50
51
# File 'lib/hash_ext/sorted.rb', line 49

def to_h
  each_with_object({}) { |(k,v),h| h[k] = v }
end

#valuesObject



29
30
31
# File 'lib/hash_ext/sorted.rb', line 29

def values
  keys.map { |k| self[k] }
end