0

I need hash like:

name[13][:sub_param1] name[13][:sub_param2]

I've tried:

name = {13: {sub_param1 => 123}}

But it is only possible if 13: is '13': (string)

0

1 Answer 1

3

I'm not sure what you're doing here, but this works:

name = { 13 => { sub_param1: 123 } }

Note that using the x: notation means that the keys are forced to symbols. If you need to use more exotic key types, which is allowed, you must use the arrow.

Sign up to request clarification or add additional context in comments.

6 Comments

Good catch. And looks like the ability to use pure integers as keys was added in Ruby version 2.0
@lurker You've been able to use anything as a key for as long as I can remember, it's been a core feature since pretty much forever. This does seem kind of insane if you come from a background like JavaScript where things are coerced to a string.
@lurker What docs? From the 1.8.7 documentation: "A Hash is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. " I'm pretty sure it pre-dates 1.8 significantly as well.
I was keying (no pun intended) in on the phrase ...not an integer index (following your bolded phrase) which was removed starting in 2.0. I suspect I misinterpreted that phrase. What does it really mean?
@lurker An Array can only use integer indexes, a Hash can use anything. I think the phrasing here was intended to mean "not necessarily an integer index". If it was removed it's probably because it was causing more confusion than intended.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.