Reputation: 470
I am creating a hash which has a single key but an array of values associated with it. I am trying to access a specific value in a specific index of the hash values array.
numbers = {fib => [1, 1, 2, 3, 5]}
If I want to access index 3 then I would say numbers.values_at("numbers").index(4). However, this does not return the value 5 but rather the entire array. Is it possible to extract a single value from that hash's value array?
I am using ruby 1.9.3 so I can only use the methods found within this ruby version.
Upvotes: 0
Views: 81
Reputation: 7326
numbers[fib][4] is the best way:
> numbers[fib]
=>[1, 2, 3, 4, 5]
> numbers[fib][4]
=> 5
Upvotes: 1
Reputation: 4837
You could try this:
numbers[fib][i]
To access position i of the array.
The values_at method returns an array of values for when you pass multiple keys, if you only need a single value (thus only passing a single key to values_at) the proper way to do it would be to pass the key directly to the hash.
If you still want to access the hashes' value array, then you need to do something like this:
numbers.values_at(fib)[0][i]
Upvotes: 1