1

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?

Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
Dark Castle
  • 1,289
  • 2
  • 9
  • 20
  • Ok so I found out that in the first snippet above I can do an event1 = event[1], then event1['modified'] and get that hash element. Can someone explain to me though why the 2nd snippet doesn't give me a nice hash? – Dark Castle Mar 12 '11 at 22:52
  • Three out of four words in "ruby beginner question hashes" is redundant. 1) The ruby tag at the bottom indicates that it's a ruby question. 2) Stating whether it's beginner or advanced isn't done here. 3) Everything is a question. – Andrew Grimm Mar 13 '11 at 22:08
  • For tips on how to debug your code, you may want to read http://stackoverflow.com/questions/3955688/how-do-i-debug-ruby-scripts – Andrew Grimm Mar 13 '11 at 22:25

2 Answers2

3

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
hoha
  • 4,418
  • 17
  • 15
0

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.

gjb
  • 6,237
  • 7
  • 43
  • 71