Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Ruby
Strange behaviour
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Jacob Fugal, post: 4508511"] Take a look at this for some clues: $ irb irb(main):001:0> events =3D {} =3D> {} irb(main):002:0> events.default =3D [] =3D> [] irb(main):003:0> events["trying"] << "hello" =3D> ["hello"] irb(main):004:0> events.default =3D> ["hello"] irb(main):005:0> events["test"] =3D> ["hello"] In short, what's happening is that when you call events["trying"] at statement 3, it returns the default value, which is an array. You then insert "hello" into that array and *change the default value*. Since you never assigned to events["trying"], it still doesn't exist. You were only getting the expected value back on re-access because of the changed default value. Try this instead: $ irb irb(main):001:0> events =3D Hash.new{ |h,k| h[k] =3D [] } =3D> {} irb(main):002:0> events.default =3D> [] irb(main):003:0> events["trying"] << "hello" =3D> ["hello"] irb(main):004:0> events.default =3D> [] irb(main):005:0> events["trying"] =3D> ["hello"] irb(main):006:0> events["test"] =3D> [] irb(main):007:0> events =3D> {nil=3D>[], "test"=3D>[], "trying"=3D>["hello"]} This produces the desired behavior, but you have to be careful, since accessing non-existent keys will pollute the keys of your hash. [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Ruby
Strange behaviour
Top