Forum: Ruby convert hash to array index value

Posted by rekha meena (rekhu)
on 2012-11-29 23:58
Attachment: ruby_file.txt (410 Bytes)
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!!!!!!
Posted by Henry Maddocks (Guest)
on 2012-11-30 00:07
(Received via mailing list)
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 `<main>'
1.9.3p327 :007 >


Henry
Posted by Robert Klemme (robert_k78)
on 2012-11-30 13:21
(Received via mailing list)
On Thu, Nov 29, 2012 at 11:58 PM, rekha meena <lists@ruby-forum.com> 
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
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.