Created
April 7, 2011 03:43
-
-
Save cjheath/906998 to your computer and use it in GitHub Desktop.
This file contains 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
#! /usr/bin/env ruby | |
# | |
# This code works (or fails!) differently on MRI, Rubinius and JRuby, | |
# also depending on whether the Fixnum monkey-patches are included. | |
# Note that the patches exist to apply a to_i to the parameter of Fixnum@eql? | |
# | |
# If Ruby's Hash claims to use only "hash" and "eql?" to store and find | |
# items, why can't the Ruby interpreters agree on *how*? | |
# | |
# In particular: | |
# 1) If Fixnum has a patched version of either method, any | |
# internal optimisations should be disabled. | |
# | |
# 2) the eql? method should be called only on the values | |
# actually stored in the hash, or only on the value we're | |
# using as a key. It should not use both, and it should not | |
# be indeterminate which one will be used. | |
# | |
class Number | |
def initialize(i) | |
@i = i | |
end | |
def eql?(a) | |
print " <Number #{@i.inspect}>.eql?(#{a.inspect})" | |
v = @i.eql?(a.to_i) | |
puts " => #{v.inspect}" | |
v | |
end | |
def to_i | |
@i | |
end | |
def hash | |
print " Getting Number(#{@i}).hash()" | |
v = @i.hash | |
puts " => #{@i.hash}" | |
v | |
end | |
end | |
class Fixnum | |
alias :orig_eql? :eql? | |
def eql?(i) | |
print " <Fixnum #{inspect}>.eql?(#{i.inspect})" | |
v = self.orig_eql?(i.to_i) | |
puts " => #{v.inspect}" | |
v | |
end | |
alias :orig_hash :hash | |
def hash | |
print " <Fixnum #{inspect}>.hash" | |
v = orig_hash | |
puts " => #{v.inspect}" | |
v | |
end | |
end | |
puts "Populating the hash:" | |
h = {} | |
20.upto(30) {|i| h[Number.new(i)] = true } | |
puts | |
puts "Looking up using Integer:" | |
i = 23 | |
p h[i] | |
puts "Looking up using Number.new(23):" | |
p h[Number.new(23)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment