Skip to content

Instantly share code, notes, and snippets.

@etiennebarrie
Created May 30, 2013 15:39
Show Gist options
  • Save etiennebarrie/5678850 to your computer and use it in GitHub Desktop.
Save etiennebarrie/5678850 to your computer and use it in GitHub Desktop.
# Using Array#assoc instead of a Hash when comparing using only ==
require 'test/unit/assertions'
include Test::Unit::Assertions
class Foo
def initialize(i)
@i = i
end
attr_reader :i
def ==(other)
@i == other.i
end
end
foo_1 = Foo.new(1)
foo_1b = Foo.new(1)
foo_2 = Foo.new(2)
assert_not_equal foo_1, foo_2
assert_equal foo_1, foo_1b
# We can't use hash grouping ability because the class Foo does not properly
# implement #hash
i_counter = Hash.new(0)
[foo_1, foo_1b, foo_2].each do |foo|
i_counter[foo] += 1
end
begin
assert_equal 2, i_counter[foo_1]
assert_equal 1, i_counter[foo_2]
rescue MiniTest::Assertion
p $!
end
# Array#assoc to the rescue :)
i_counter = []
[foo_1, foo_1b, foo_2].each do |foo|
assoc = i_counter.assoc(foo)
if assoc
assoc[-1] += 1
else
i_counter << [foo, 1]
end
end
assert_equal 2, i_counter.assoc(foo_1).last
assert_equal 1, i_counter.assoc(foo_2).last
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment