Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby

finding a value in a hash?

I'm having trouble displaying a value.

When I call @guidelines the page displays

[#<Guideline id: 25, title: "Bananas", content: "test me", hospital: "My Hospital", created_at: "2013-02-04 04:06:22", updated_at: "2013-02-07 01:37:49", user_id: 10>]

I want it to display "My Hospital"

But when I call

@guidelines.hospital 

I get 'undefined method `hospital' for #<Array:0x007f8a937a1e38>'

Have also tried

@guidelines.index(hospital)

and a few others but cannot seem to get it to work.

Can anyone help?

2 Answers

Jason Seifer
STAFF
Jason Seifer
Treehouse Guest Teacher

Hey Tessa,

The @guidelines variable is an array. You'll need to iterate over the individual items in order to access it. Try something like this:

<% @guidelines.each do |guideline| %>
  <%= guideline.hospital %>
<% end %>

Thanks for the reply Jason. I did manage to work this out - guideline.hospital is the same for each guideline on this page so I only wanted it printed out once. I did it as follows:

<% @guidelines.each_with_index do |guideline, index| %>
<% if index==0 %>
<%= guideline.hospital %>

<% end %>