Skip to content

Instantly share code, notes, and snippets.

@olly
Created April 5, 2017 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olly/806659d7bb5f98e34bace341019e842c to your computer and use it in GitHub Desktop.
Save olly/806659d7bb5f98e34bace341019e842c to your computer and use it in GitHub Desktop.
Ruby Set#include? strangeness
require 'minitest/autorun'
require 'set'
class Foo
def initialize(s)
@s = s
end
def ==(other)
@s == other
end
def eql?(other)
@s.eql?(other)
end
def hash
@s.hash
end
end
module FooEquality
def ==(other)
if other.is_a?(Foo)
other == self
else
super(other)
end
end
def eql?(other)
if other.is_a?(Foo)
other.eql?(self)
else
super(other)
end
end
end
class String
prepend FooEquality
end
class TestSet < MiniTest::Unit::TestCase
def setup
@foo = Foo.new("foo")
@set = Set.new([@foo])
@hsh = { @foo => true }
end
def test_set_include_obj
assert @set.include?(@foo)
end
def test_set_include_str
assert @set.include?("foo")
end
def test_hsh_include_obj
assert @hsh.include?(@foo)
end
def test_hsh_include_str
assert @hsh.include?("foo")
end
def test_eql
assert @foo.eql?("foo")
end
def test_hash
assert @foo.hash == "foo".hash
end
end
Run options: --seed 36646
# Running:
......
Finished in 0.001399s, 4288.7777 runs/s, 4288.7777 assertions/s.
6 runs, 6 assertions, 0 failures, 0 errors, 0 skips
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment