Last active
December 21, 2015 01:09
-
-
Save sirupsen/6225767 to your computer and use it in GitHub Desktop.
Ruby 2.0.0 coerce incompatibility.
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
| # The issue here, is that when Ruby encounters an expression like: | |
| # | |
| # 5 < Mass.new(10) | |
| # | |
| # The Fixnum doesn't know how to compare itself to a Mass. However, a Mass object knows | |
| # how to compare itself with a Fixnum. Ruby calls #coerce on 5, to switch the parameters | |
| # around, so now we have: | |
| # | |
| # Mass.new(10) > 5 | |
| # | |
| # In 1.9, it will just try to call #coerce, however, in 2.0 it will call #respond_to?(:coerce) | |
| # first. This in 1.9, you could just delegate to a fixnum with method_missing, as is done below. | |
| # But that won't work in 2.0, since #respond_to? would not pick that up. | |
| class Mass | |
| include Comparable | |
| attr_reader :amount | |
| def initialize(amount) | |
| @amount = amount | |
| end | |
| def <=>(other) | |
| self.amount <=> other | |
| end | |
| # This works on 1.9 and 2.0 | |
| # def coerce(other) | |
| # [other, self.amount] | |
| # end | |
| # This works only on 1.9 | |
| def method_missing(meth, *args) | |
| @amount.send(meth, *args) | |
| end | |
| end | |
| p 5 < Mass.new(10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment