Ruby 如何在ERB文件中输出多维哈希?

Ruby 如何在ERB文件中输出多维哈希?,ruby,sinatra,erb,Ruby,Sinatra,Erb,我需要一些帮助来打印哈希值。在我的web.rb文件中,我有: class Main < Sinatra::Base j = {} j['Cordovan Communication'] = {:title => 'UX Lead', :className => 'cordovan', :images => ['http://placehold.it/350x150','http://placehold.it/350x150','http://placeh

我需要一些帮助来打印哈希值。在我的web.rb文件中,我有:

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>
想想@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']}
}
然后请记住,对散列的每个调用都会向块传递一个键和一个值,您将看到:

@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 %> 

Ruby哈希没有自动创建方法,例如,您不能调用job.title,因为哈希对象上没有title方法。相反,您可以调用job[:title]


还要注意@jobs是一个散列,而不是一个数组,因此您可能希望调用@jobs.each而不是@jobs.each。可以使用@jobs.each,但在这种情况下,它不会提供您期望的结果。

当迭代器不输出您想要的内容时,请尝试检查@jobs.each.to_a输出的内容。Hasheach和Hasheach_对是相同的方法。检查