Dark Castle
Dark Castle

Reputation: 1299

Why can't I access an item from this Ruby hash?

I have a data structure that looks like this:

@results['events'].each do |event|
  event.inspect
end
["event", {"modified"=>"2011-03-04 12:39:13", "groups"=>nil, "country_name"=>"United States", "city_name"=>"Morrison", "latitude"=>39.653992, "title"=>"Red Rocks Indian Art Show", "region_name"=>"Colorado"}] 

OR

@results['events']['event'].each do |event|
  event.inspect
end
["modified", "2011-03-04 12:39:13"] ["groups", nil] ["country_name", "United States"] ["city_name", "Morrison"] ["latitude", 39.653992] ["title", "Red Rocks Indian Art Show"]

I would think that I could do something like this:

@results['events']['event'].each do |event|
  event['modified']
end

But when I do I get this: can't convert String into Integer on the line that contains: event['modified']

What am I doing wrong?

Upvotes: 1

Views: 2498

Answers (2)

gjb
gjb

Reputation: 6317

Rails only allows numeric indexes for arrays.

Try restructuring your data structure as follows:

events = [
           {
             :name => "event",
             :modified => "2011-03-04 12:39:13",
             :groups => nil,
             :country_name => "United States",
             :city_name => "Morrison",
             :latitude => 39.653992,
             :title => "Red Rocks Indian Art Show",
             :region_name => "Colorado"
           }
         ]

It makes more sense to have an array of hashes: one hash per event. Also using symbols as hash keys is cleaner and more efficient.

Hope that helps.

Upvotes: 0

hoha
hoha

Reputation: 4428

inspect returns a string. each discards values returned from block so actually what you see in output is a value of object on which each is called. Use p obj to print obj.

You get "can't convert String into Integer" because if you call each on Hash instance and pass single-parameter block to it this block is called with array representing key-value pair (like [key, value]). In event['modified'] you're trying to get a value from array using String index. Arrays accept only integer indices so Ruby tries to make a conversion and fails.

What you want is

@results['events']['event'].each do |eventProperty, eventPropertyValue|
  # do something here
end

Upvotes: 3

Related Questions