valid hash keys 
Author Message
 valid hash keys

unlike perl, ruby treats 1 and '1' differently in hash keys:

$ irb
irb(main):001:0> a={}
irb(main):002:0> a[1]=1
irb(main):003:0> a['1']='1'
irb(main):004:0> a
{1=>1, "1"=>"1"}

so what are the range the valid values for hash keys? can i, like in
python, use "immutable lists"/tuples as hash keys?

--
dave



Thu, 06 Jan 2005 00:12:01 GMT  
 valid hash keys

Quote:
> unlike perl, ruby treats 1 and '1' differently in hash keys:

This is largely because:

* Perl will happily change numbers to strings (and back), sometimes
when you're least expecting it.

* Perl only uses strings as hash keys.

Quote:
> so what are the range the valid values for hash keys? can i, like
> in python, use "immutable lists"/tuples as hash keys?

You can use any object.

$ ri Object.hash
------------------------------------------------------------
Object#hash
     obj.hash -> aFixnum
------------------------------------------------------------------------
     Generates a Fixnum hash value for this object. This function must
     have the property that a.eql?(b) implies a.hash == b.hash. The
hash
     value is used by class Hash. Any hash value that exceeds the
     capacity of a Fixnum will be truncated before being used.

--
Ned Konz
http://bike-nomad.com
GPG key ID: BEEA7EFE



Thu, 06 Jan 2005 00:17:13 GMT  
 valid hash keys


Quote:
> so what are the range the valid values for hash keys? can i, like in
> python, use "immutable lists"/tuples as hash keys?

As Ned Konz has already replied, you can use any object as a hash key since
they all respond to the "hash" message. But since Ruby arrays (and strings,
for that matter) aren't immutable you want to be careful about using them as
hash keys. Specifically, if you use a mutable object as a hash key and then
change its value, be sure to call rehash on the Hash object. See this page
from "Programming Ruby":

    http://www.rubycentral.com/book/ref_c_hash.html#Hash.rehash

for a short and sweet example.



Thu, 06 Jan 2005 01:08:26 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. hash as key in hash

2. Hash.new(Hash.new) doesn't use Hash.new as default value

3. WeakDictionary value 0 for valid key

4. Is NULL a valid one word key value for Tcl_CreateHashEntry

5. Accessing hash values sorted by their keys

6. sort the hash keys

7. Checking hash key's and values, with case insensitivity

8. Primary Key Hash help

9. Auto-quoting simple hash keys?

10. Hash.keys Q

11. using my own objects as hash keys - a question

12. Symbols, and their use as hash keys

 

 
Powered by phpBB® Forum Software