Convert hash to array index value

when we convert a hash to array.it takes one key value pair as a one
argument
and it gives the output as a key value pair…but if i give just index
number and want output according to that it shows “nil” why???

If it is working as an array then it should show me some value regarding
the index number…
Please correct me if i am wrong!!!

On 30/11/2012, at 11:58 AM, rekha meena wrote:

when we convert a hash to array.it takes one key value pair as a one
argument
and it gives the output as a key value pair…but if i give just index
number and want output according to that it shows “nil” why???

If it is working as an array then it should show me some value regarding
the index number…
Please correct me if i am wrong!!!

person.to_a returns a new Array, it doesn’t convert person to an Array.

1.9.3p327 :001 > person = {‘name’=>‘jack’,‘age’=>25,‘city’=>‘abc’}
=> {“name”=>“jack”, “age”=>25, “city”=>“abc”}
1.9.3p327 :002 > person.to_a
=> [[“name”, “jack”], [“age”, 25], [“city”, “abc”]]
1.9.3p327 :003 > person
=> {“name”=>“jack”, “age”=>25, “city”=>“abc”}
1.9.3p327 :004 > person = person.to_a
=> [[“name”, “jack”], [“age”, 25], [“city”, “abc”]]
1.9.3p327 :005 > person[1]
=> [“age”, 25]
1.9.3p327 :006 > person[‘name’]
TypeError: can’t convert String into Integer
from (irb):6:in []' from (irb):6 from /Users/henry/.rvm/rubies/ruby-1.9.3-p327/bin/irb:16:in
1.9.3p327 :007 >

Henry

On Thu, Nov 29, 2012 at 11:58 PM, rekha meena [email protected]
wrote:

when we convert a hash to array.it takes one key value pair as a one
argument
and it gives the output as a key value pair…but if i give just index
number and want output according to that it shows “nil” why???

What “index number”? A Hash is not indexed by number - unless you
specifically use numbers as keys.

If it is working as an array then it should show me some value regarding
the index number…
Please correct me if i am wrong!!!

A Hash is not working as an Array. What do you mean?

Kind regards

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs