Skip to content

Instantly share code, notes, and snippets.

@suchi
Created May 12, 2011 06:55
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 suchi/968063 to your computer and use it in GitHub Desktop.
Save suchi/968063 to your computer and use it in GitHub Desktop.
hamamatsu.rb#3 protectedなインスタンス変数getterを利用した比較
class Foo
include Comparable
def initialize(x, y)
@x = x
@y = y
end
def <=>(rhs)
return nil unless rhs.instance_of? Foo
if @x == rhs.x
@y <=> rhs.y
else
@x <=> rhs.x
end
end
protected
attr_reader :x, :y
end
# a = Foo.new(2, 3)
# aa = Foo.new(2, 3)
# b = Foo.new(4, 5)
#
# puts a == aa #=> true
# puts a == b #=> false
# puts a < aa #=> false
# puts a < b #=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment