Class: Hash::Sorted

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

Class Method Summary collapse

Instance Method Summary collapse

Methods included from DeepFreezable

#deep_freeze

Constructor Details

#initialize(hash = {}, direction = :asc, &sort_criteria) ⇒ Sorted

Returns a new instance of Sorted.



19
20
21
22
23
# File 'lib/hash_ext/sorted.rb', line 19

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



60
61
62
# File 'lib/hash_ext/sorted.rb', line 60

def ascending(hash={}, &sort_criteria)
  new hash, :asc, &sort_criteria
end

.descending(hash = {}, &sort_criteria) ⇒ Object Also known as: desc



65
66
67
# File 'lib/hash_ext/sorted.rb', line 65

def descending(hash={}, &sort_criteria)
  new hash, :desc, &sort_criteria
end

Instance Method Details

#eachObject Also known as: each_pair



34
35
36
37
# File 'lib/hash_ext/sorted.rb', line 34

def each
  return enum_for(:each) unless block_given?
  keys.each { |k| yield k, self[k]}
end

#each_keyObject



40
41
42
43
# File 'lib/hash_ext/sorted.rb', line 40

def each_key
  return enum_for(:each_key) unless block_given?
  keys.each { |k| yield k }
end

#each_valueObject



45
46
47
48
# File 'lib/hash_ext/sorted.rb', line 45

def each_value
  return enum_for(:each_value) unless block_given?
  keys.each { |k| yield self[k] }
end

#keysObject



25
26
27
28
# File 'lib/hash_ext/sorted.rb', line 25

def keys
  sorted_keys = @hash.sort_by(&sort_criteria).map { |k,v| k }
  direction == :asc ? sorted_keys : sorted_keys.reverse
end

#to_hObject



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

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

#valuesObject



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

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