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

时间:2013-03-11 15:47:18

标签: 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://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>

2 个答案:

答案 0 :(得分: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 %> 

答案 1 :(得分:2)

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

另请注意,@jobs是哈希,而不是数组,因此您可能希望调用@jobs.each_pair而不是@jobs.each。可以使用@jobs.each,但在这种情况下,它不会给你你所期望的。