Created
November 9, 2012 07:48
-
-
Save sandbochs/4044309 to your computer and use it in GitHub Desktop.
Ruby Hash Example
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
http://blog.sandbochs.com | |
# The hash method produces a different value | |
# every time you load up ruby | |
# because it is based off of the object_id | |
1.hash => 3843363811812838534 | |
num = 1 | |
num.hash => 3843363811812838534 | |
# Strings override Object's hash method | |
# The hash function is based on the characters in the string | |
"apples".hash => 1951414395381147893 | |
string = "apples" | |
string.hash => 1951414395381147893 | |
"Apples".hash => -3796558981278204666 | |
# A new Apple class where all apples weigh 6 oz | |
class Apple | |
def initialize | |
@weight = 6 | |
end | |
end | |
a1 = Apple.new | |
a2 = Apple.new | |
# The hash methods produce different values | |
a1.hash => -3674294693357128426 | |
a2.hash => 3276174667199791386 | |
directory = {a1 => "apple shack"} | |
directory[a1] => "apple shack" | |
directory[a2] => nil | |
# Let's override the hash function | |
class Apple | |
def hash | |
5 * @weight | |
end | |
end | |
# The hash methods produce the same hash | |
# for apples that are the same weight | |
a1.hash => 30 | |
a2.hash => 30 | |
a1 == a2 => false | |
# Still nil though... | |
directory = {a1 => "apple shack"} | |
directory[a1] => "apple shack" | |
directory[a2] => nil | |
# Right, the hash table will compare the object | |
# you are looking up with the object | |
# inside the bucket! Override == operator... | |
class Apple | |
attr_reader :weight | |
def ==(other) | |
weight == other.weight | |
end | |
end | |
a1.hash => 30 | |
a2.hash => 30 | |
a1 == a2 => true | |
# What?! still nil! | |
directory[a1] => "apple shack" | |
directory[a2] => nil | |
# Ruby's implementation of hashes actually | |
# compares with the eql? method, not == | |
class Apple | |
def eql?(other) | |
self == other | |
end | |
end | |
a1.hash => 30 | |
a2.hash => 30 | |
a1.eql? a2 => true | |
# COOL HUH!? | |
directory[a1] => "apple shack" | |
directory[a2] => "apple shack" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice example!