Forum: Ruby What does this hash do? Is this a hash?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B1445f6a5d2b63683c08576bf929571e?d=identicon&s=25 ralf (Guest)
on 2006-04-03 11:31
(Received via mailing list)
Hi,
I'm tryin some hash functionality and came accros this in irb:

hash = Hash.new("")
=> {}
hash["a"] << "b"
=> "b"
hash["a"]
=> "b"
hash
=> {}
hash.size
=> 0
hash["alskj"]
=> "b"


What ist this? Prog.Ruby says, that by "hash = Hash.new("")" hash has a
default value for missing keys.
How can I set a value for a keys with the <<-method?

Thanks in advance
Ralf
956f185be9eac1760a2a54e287c4c844?d=identicon&s=25 ts (Guest)
on 2006-04-03 11:37
(Received via mailing list)
>>>>> "r" == ralf  <stark.dreamdetective@googlemail.com> writes:

r> hash = Hash.new("")
r> => {}
r> hash["a"] << "b"

 When you write this :
  1) ruby return the default value for the hash ('a' don't exist as a
key)
  2) concatenate "b" to this default value (see String#<<)

 Finally you have modified the default value for the hash, and you can
see
 this here :

r> hash["alskj"]
r> => "b"

  ruby now give the new default value



Guy Decoux
B1445f6a5d2b63683c08576bf929571e?d=identicon&s=25 ralf (Guest)
on 2006-04-03 11:50
(Received via mailing list)
Thanks!
I think, it's a bit confusing, that the dafault value is accessed by
"hash["a"]", i.e. the term for accessing a value according to key "a".

The constuctor "Hash.new {block}" works for me:
ahash = Hash.new {|hash,key| hash[key] = ""}
=> {}
ahash["a"] << "vier"
=> "vier"
ahash
=> {"a"=>"vier"}

Best regards
Ralf
Bf6862e2a409078e13a3979c00bba1d6?d=identicon&s=25 Gregory Seidman (Guest)
on 2006-04-03 13:49
(Received via mailing list)
On Mon, Apr 03, 2006 at 06:34:50PM +0900, ts wrote:
} >>>>> "r" == ralf  <stark.dreamdetective@googlemail.com> writes:
}
} r> hash = Hash.new("")
} r> => {}
} r> hash["a"] << "b"
}
}  When you write this :
}   1) ruby return the default value for the hash ('a' don't exist as a
key)
}   2) concatenate "b" to this default value (see String#<<)
}
}  Finally you have modified the default value for the hash, and you can
see
}  this here :
}
} r> hash["alskj"]
} r> => "b"
}
}   ruby now give the new default value

This has to be the most frequently asked question on this list. Why
isn't it
in the FAQ at http://www.rubygarden.org/faq/main/all ?

} Guy Decoux
--Greg
This topic is locked and can not be replied to.