Problem accessing hash table

A

Anukul Singhal

Hi,

I am facing the following problem, when using the following code
snippet:

c = []
c.push({:name => 'xyz', :class => 'm70', :title => 'yes'})

Now, puts c gives me the output as classm70namexyztitleyes

My Aim is to access the :name attribute of the hash table that is being
pushed into the c array. I tried the following:

puts c[:name] , gives an error - p046hashes.rb:10:in `[]': Symbol as
array index (TypeError)
from p046hashes.rb:10

Can anyone help as to how I can access the value of the hash table
defined in the array?

Thanks,
Anukul
 
T

Todd Benson

Hi,

I am facing the following problem, when using the following code
snippet:

c = []
c.push({:name => 'xyz', :class => 'm70', :title => 'yes'})

Now, puts c gives me the output as classm70namexyztitleyes

My Aim is to access the :name attribute of the hash table that is being
pushed into the c array. I tried the following:

puts c[:name] , gives an error - p046hashes.rb:10:in `[]': Symbol as
array index (TypeError)
from p046hashes.rb:10

Can anyone help as to how I can access the value of the hash table
defined in the array?

Thanks,
Anukul
--

In your example, you have a Hash instance as an element of an Array
instance. That doesn't sound like what you probably want. But if it
is, and since it is the first element in your array c, you can get
that hash with c[0].

puts c[0][:name]

hth,
Todd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top