Understanding array/hash

Hello,

I'm having little hard time understanding following code

<pre>
conf = {
        :hash_key =>
                {
                        'hash_string' => {
                                :hash1 => 'get_me',
                                :hash2 => 'get_me',
                        }
                }
}

puts conf[:hash_key].first #returns Array ?
puts conf[:hash_key].first[0] #returns string "hash_string"
puts conf[:hash_key].first[1] #returns hash that i want
</pre>
http://pastebin.com/6qfE1HDm

Question is, why Ruby returns Array on conf[:hash_key].first ?
The ideal method for me to get hash "hash_string" would be
`conf.first.first` but this returns string "hash_string".

This might be newbie question but I'm learning Ruby on my own :slight_smile:

Cheers

···

--
Posted via http://www.ruby-forum.com/.

Hello,

I'm having little hard time understanding following code

<pre>
conf = {
        :hash_key =>
                {
                        'hash_string' => {
                                :hash1 => 'get_me',
                                :hash2 => 'get_me',
                        }
                }
}

puts conf[:hash_key].first #returns Array ?
puts conf[:hash_key].first[0] #returns string "hash_string"
puts conf[:hash_key].first[1] #returns hash that i want
</pre>
conf = { :hash_key => { 'hash - Pastebin.com

Question is, why Ruby returns Array on conf[:hash_key].first ?

Because conf[:hash_key] is a Hash and a Hash provides two values per iteration:

irb(main):004:0> h = {1=>2,3=>4}
=> {1=>2, 3=>4}
irb(main):005:0> h.first
=> [1, 2]
irb(main):006:0> h.each {|a| p a}
[1, 2]
[3, 4]
=> {1=>2, 3=>4}
irb(main):007:0> h.to_a
=> [[1, 2], [3, 4]]

The ideal method for me to get hash "hash_string" would be
`conf.first.first` but this returns string "hash_string".

No. Since all these are Hashes you better use keys to do Hash lookups
instead of positional lookups (order is generally not guaranteed in a
Hash although Ruby's Hash keeps insertion order):

irb(main):018:0> conf[:hash_key]['hash_string']
=> {:hash1=>"get_me", :hash2=>"get_me"}

Kind regards

robert

···

On Wed, Aug 28, 2013 at 12:11 PM, Igor Konforti <lists@ruby-forum.com> wrote:

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/