Ruby On Rails: Accessing Array?

Go To StackoverFlow.com

1

I have an array stored in a variable temp which looks like this:

temp.inspect output :

[#"Marlana Letelier", "completed_at"=>nil, "status"=>"incomplete", "name"=>nil, "lead_move_date"=>"2012-06-17 00:00:00", "archive_time"=>nil, "stop_time"=>nil, "priority"=>"2", "assigned_to_user_firstname"=>"Vanessa", "notes"=>"", "created_by_id"=>nil, "id"=>"804005", "assigned_to_id"=>"1", "dn_email_id"=>nil, "outcomes_string"=>"other", "lead_id"=>"101139", "flavor"=>"PhonecallTask", "stringified_parameters"=>"{\n'purpose' => 'continued contact attempt',\n'phone_number' => '361-946-9905',\n}", "created_at"=>"2011-12-21 13:29:07", "start_time"=>"2012-04-04 17:00:00"}>]

temp.class specifies it as an array but temp[1] doesn't output anything.

How do I access the elements ?

EDIT:
1) Temp either had nothing, 1 object or multiple objects
2) Check for nil
3) Get each object out
4) access the attributes

2012-04-05 17:08
by sunny31


0

Although your inspect output looks wrong (I think you're missing some text that came out in <...> tags) it looks like you have an array with a single item. Verify this assumption by outputting temp.length.

Since Arrays in Ruby are 0-indexed, try temp[0] or temp.first.

2012-04-05 17:12
by Phrogz
Temp.length is 1 . So how do we go about extracting that data - sunny31 2012-04-05 17:17
@sunny31 Correct; thus temp[1] is trying to access an element that does not exist. You want temp[0] or temp.first - Phrogz 2012-04-05 17:18
That just spits out # and nothing else. Tried both temp[0] and temp.firs - sunny31 2012-04-05 17:19
@sunny31 That's because it's actually outputting something like #<MyClass ....>, but you are outputting it to the HTML page where the browser is misinterpreting that as an HTML element. Either HTML escape your output, or view source on your browser, or use p ... to print the value to the console instead of the view - Phrogz 2012-04-05 17:23
So a little poking results to this: temp is an array which is storing an object.

Now how do I go about accessing that object and its attributes ?

Ruby 1.8. - sunny31 2012-04-05 18:12

@sunny31 First, get the object. Then, invoke methods on the object, or (if you must) use instance_variable_get to directly access instance variables. Read the documentation for the class of object you have received, and the modules it mixes in, and the classes from which it inherits, to find the methods available - Phrogz 2012-04-05 18:19
@sunny31 Note that if this answer helped you and solved your question, you should "accept" it by clicking the checkmark - Phrogz 2012-04-05 20:26
Ads