Skip to content

Commit

Permalink
Merge pull request #46 from bdunne/sorting_hashes
Browse files Browse the repository at this point in the history
Extract Hash sorting from manageiq-gems-pending
  • Loading branch information
Fryguy authored Jul 17, 2017
2 parents b4bd8d3 + 78fd8a2 commit a9b8d89
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/more_core_extensions/core_ext/hash.rb
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
require 'more_core_extensions/core_ext/hash/nested'
require 'more_core_extensions/core_ext/hash/deletes'
require 'more_core_extensions/core_ext/hash/nested'
require 'more_core_extensions/core_ext/hash/sorting'
20 changes: 20 additions & 0 deletions lib/more_core_extensions/core_ext/hash/sorting.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
module MoreCoreExtensions
module HashSortBang
def sort!(*args, &block)
sorted = sort(*args, &block)
sorted = self.class[sorted.to_a] unless sorted.instance_of?(self.class)
replace(sorted)
end
end

module HashSortByBang
def sort_by!(*args, &block)
sorted = sort_by(*args, &block)
sorted = self.class[sorted.to_a] unless sorted.instance_of?(self.class)
replace(sorted)
end
end
end

Hash.send(:include, MoreCoreExtensions::HashSortBang) unless Hash.method_defined?(:sort!)
Hash.send(:include, MoreCoreExtensions::HashSortByBang) unless Hash.method_defined?(:sort_by!)
21 changes: 21 additions & 0 deletions spec/core_ext/hash/sorting.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
describe Hash do
it "#sort!" do
h = {:x => 1, :b => 2, :y => 3, :a => 4}
h_id = h.object_id

h.sort!

expect(h.keys).to eq([:a, :b, :x, :y])
expect(h.object_id).to eq(h_id)
end

it "#sort_by!" do
h = {:x => 1, :b => 2, :y => 3, :a => 4}
h_id = h.object_id

h.sort_by! { |k, _v| k }

expect(h.keys).to eq([:a, :b, :x, :y])
expect(h.object_id).to eq(h_id)
end
end

0 comments on commit a9b8d89

Please sign in to comment.