Reputation: 3176
I need some help printing the values of my hash. In my "web.rb" file I have:
class Main < Sinatra::Base
j = {}
j['Cordovan Communication'] = {:title => 'UX Lead', :className => 'cordovan', :images => ['http://placehold.it/350x150','http://placehold.it/350x150','http://placehold.it/350x150']}
j['Telia'] = {:title => 'Creative Director', :className => 'telia', :images => ['http://placehold.it/350x150','http://placehold.it/350x150','http://placehold.it/350x150','http://placehold.it/350x150']}
get '/' do
@jobs = j
erb :welcome
end
end
In "welcome.rb" I'm printing the values of the hash, but it doesn't work:
<% @jobs.each do |job| %>
<div class="row">
<div class="span12">
<h2><%=h job.title %></h2>
</div>
</div>
<% end %>
Here's my error message:
NoMethodError at / undefined method `title' for #<Array:0x10c144da0>
Upvotes: 0
Views: 5369
Reputation: 6419
There's no automatic method creation for Ruby hashes, e.g., you can't call job.title
, since there is no title
method on Hash
objects. Instead you can call job[:title]
.
Also note that @jobs
is a hash, not an array, so you probably want to call @jobs.each_pair
rather than @jobs.each
. It's possible to use @jobs.each
, but in this case it's not going to give you what you expect.
Upvotes: 2
Reputation: 46657
Think what @jobs
looks like:
@jobs = {
'Cordovan Communication' => {
:title => 'UX Lead',
:className => 'cordovan',
:images => ['http://placehold.it/350x150','http://placehold.it/350x150','http://placehold.it/350x150']},
'Telia' => {
:title => 'Creative Director',
:className => 'telia',
:images => ['http://placehold.it/350x150','http://placehold.it/350x150','http://placehold.it/350x150','http://placehold.it/350x150']}
}
Then remember that each
called on a hash passes a key and a value to the block, and you'll see that you have:
@jobs.each do |name, details|
# On first step, name = 'Cordovan Communication', details = {:title => 'UX Lead', ...}
end
So what you want is probably:
<% @jobs.each do |name, details| %>
<div class="row">
<div class="span12">
<h2><%=h details[:title] %></h2>
</div>
</div>
<% end %>
Upvotes: 7