Created
April 18, 2012 21:17
-
-
Save seamusabshere/2416615 to your computer and use it in GitHub Desktop.
random look at ActiveSupport::OrderedHash versus HashWithIndifferentAccess
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'minitest/spec' | |
require 'minitest/autorun' | |
require 'minitest/reporters' | |
MiniTest::Unit.runner = MiniTest::SuiteRunner.new | |
MiniTest::Unit.runner.reporters << MiniTest::Reporters::SpecReporter.new | |
require 'securerandom' | |
require 'active_support/core_ext' | |
seen = [] | |
keys = [] | |
10.times do | |
k = SecureRandom.hex(2) | |
while seen.include?(k) | |
k = SecureRandom.hex(2) | |
end | |
seen << k | |
if rand > 0.5 | |
k = k.to_sym | |
end | |
keys << k | |
end | |
normal_hsh = {} | |
ordered_hsh = ActiveSupport::OrderedHash.new | |
keys.each do |k| | |
v = rand(1e11) | |
normal_hsh[k] = v | |
ordered_hsh[k] = v | |
end | |
describe "key order" do | |
describe "in normal hashes" do | |
it "won't stay the same (unless we're in 1.9)" do | |
if RUBY_VERSION >= '1.9' | |
normal_hsh.keys.must_equal keys | |
else | |
normal_hsh.keys.wont_equal keys | |
end | |
end | |
it "won't stay the same when converted to hash with indiff access (duh)" do | |
normal_hsh.with_indifferent_access.keys.wont_equal keys.map(&:to_s) | |
end | |
end | |
describe "with ActiveSupport::OrderedHash" do | |
it "will stay the same" do | |
ordered_hsh.keys.must_equal keys | |
end | |
it "will stay the same when converted to hash with indiff access" do | |
ordered_hsh.with_indifferent_access.keys.must_equal keys.map(&:to_s) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment