【问题标题】:How do I output a multidimensional hash in ERB files?如何在 ERB 文件中输出多维哈希?
【发布时间】:2013-03-12 00:20:59
【问题描述】:

我需要一些帮助来打印我的哈希值。在我的“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.each.to_a 输出的内容。

标签: ruby sinatra erb


【解决方案1】:

想想@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,但在这种情况下,它不会给你所期望的。

    【讨论】:

    猜你喜欢
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    相关资源
    最近更新 更多