2013-03-11 22 views
0

我需要一些幫助來打印我的散列值。在我的「web.rb」文件我有:如何在ERB文件中輸出多維散列?

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 

在「welcome.rb」我打印的哈希值,但它不工作:

<% @jobs.each do |job| %> 
    <div class="row"> 
     <div class="span12"> 
      <h2><%=h job.title %></h2> 
     </div> 
    </div> 
<% end %> 

這裏是我的錯誤信息:

NoMethodError at/undefined method `title' for #<Array:0x10c144da0> 
+0

當迭代器不輸出你想要的內容時,嘗試檢查'@ jobs.each.to_a'輸出的內容。 – nicooga 2013-03-11 16:04:07

回答

6

想想@jobs的樣子:

@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']} 
} 

然後記得each呼籲哈希通過一個鍵和一個值來將擋,你會看到您有:

@jobs.each do |name, details| 
    # On first step, name = 'Cordovan Communication', details = {:title => 'UX Lead', ...} 
end 

所以,你想要什麼大概是:

<% @jobs.each do |name, details| %> 
    <div class="row"> 
     <div class="span12"> 
      <h2><%=h details[:title] %></h2> 
     </div> 
    </div> 
<% end %> 
2

沒有爲Ruby散列自動創建方法,例如,您不能調用job.title,因爲Hash對象上沒有title方法。相反,您可以撥打job[:title]

還要注意的是@jobs是一個哈希,而不是一個數組,所以你可能要調用@jobs.each_pair而非@jobs.each。可以使用@jobs.each,但在這種情況下,它不會給你所期望的。

+1

'Hash#each'和'Hash#each_pair'是相同的方法。檢查[文檔](http://ruby-doc.org/core-2.0/Hash.html#method-i-each)。 – 2013-03-11 16:19:23

+0

你是對的,謝謝。 – 2013-03-11 16:20:26