Last active
December 10, 2015 21:29
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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). | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yep this is a nice one.
$gem install approximately