Skip to content

Instantly share code, notes, and snippets.

@echristopherson
Created March 1, 2012 01:04
Show Gist options
  • Save echristopherson/1946368 to your computer and use it in GitHub Desktop.
Save echristopherson/1946368 to your computer and use it in GitHub Desktop.
How to make array subtraction only compare certain fields of elements?
#!/usr/bin/env ruby
C = Struct.new :a, :b
c1 = C.new 1, 2
c2 = C.new 1, 2
c3 = C.new 3, 4
puts "[c1] - [c2]: #{[c1] - [c2]}"
c2.b = 3
puts 'set c2.b to 3'
puts "[c1] - [c2]: #{[c1] - [c2]}"
class C
def <=>(other)
a <=> other.a
end
def eql?(other)
a.eql? other.a
end
def ==(other)
a == other.a
end
end
puts 'defined comparator on C that only compares .a'
puts "[c1] - [c2]: #{[c1] - [c2]}"
puts "[c3] - [c2]: #{[c3] - [c2]}"
@echristopherson
Copy link
Author

Output:

ruby array_subtraction_test.rb
[c1] - [c2]: []
set c2.b to 3
[c1] - [c2]: [#]
defined comparator on C that only compares .a
[c1] - [c2]: [#]
[c3] - [c2]: [#]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment