Hi,
In message "[ruby-talk:02254] Hashing"
on 00/03/30, mrilu <mrilu / ale.cx> writes:
|class OpenStruct
| def initialize(hash=nil)
| @table = {}
| if hash
| for k,v in hash
| @table[k] = v
| end
| end
| end
|
|I think we're trying to make copy of hash 'hash' to @table. Why don't we
|say:
| @table = hash.dup
|or
| @table = hash.clone
|or
| @table = Hash.new.replace hash
No specific reason. `dup' is preferable.
|Now some other points of Hash. First about documentation. This excerpt is
|from my html-version of 1.4 documents.
|
|dup
| Returns a newly created hash table which has the save keys
| and values to the receiver. clone returns the complete
| copy of the original hash table, including freeze status
| and instance variables. On the other hand, dup copies the
| hash table containts.
|
|Note: I didn't see any other docs for Hash.clone.
|I try to fix few things here, but English is not my mother tongue so this
|just can't be right:
|
|dup
| Returns a newly created hash table which has same keys and values
| as the original hash instance. dup differs from clone by copying
| only hash contents (that is key,value-pairs).
| Example:
| foo = {"key"=>"value", "baz"=>"zak"}
| bar = foo.dup
| print bar[baz] # => "zak"
|
|clone
| Returns a newly created hash table which is a complete copy of the
| original hash instance. clone differs from dup by copying original
| hash table completely including key,value-pairs, freeze status and
| instance variables.
| Example:
| ...
|
|I'd like to see good examples for different copying strategies too
|(shallow, deep).
It's clearly stated in Dave&Andy's book. I will fix the reference in
near future.
|It seems that invert makes clone (or duplicate) of it's keys and values.
|If this is important at all it should make it's way into documentation!
Yes. Let me add this in my ToDo list.
matz.