Skip to content

Instantly share code, notes, and snippets.

@jimweirich
Last active December 10, 2015 21:29
Show Gist options
  • Save jimweirich/4495753 to your computer and use it in GitHub Desktop.
Save jimweirich/4495753 to your computer and use it in GitHub Desktop.
Evidently I'm rusty on my Ruby coercion rules, because the following surprised me.
class ApproximateNumber
attr_reader :number, :delta
def initialize(number, delta)
@number = number
@delta = delta
end
def ==(value)
(number-value).abs <= delta
end
def to_s
"<Approximatly #{number} +/- #{delta}>"
end
end
def about(n, delta)
ApproximateNumber.new(n, delta)
end
# Expected this to work because of the == operator in
# ApproximateNumber.
about(10, 0.01) == 10.001 # => true
# Didn't expect this to work without some kind of coercion magic. But
# it does.
10.001 == about(10, 0.01) # => true
# EXPLAINATION:
#
# Evidently, Numeric comparisons will reverse delegate the == operator
# if the compared object isn't numeric. Nice.
# (Learn something new every day).
@julik
Copy link

julik commented Jan 10, 2013

Yep this is a nice one.

$gem install approximately

@julik
Copy link

julik commented Jan 15, 2013

By the way <=> works too.

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