ruby-on-rails - 将不同的 HTML5 格式应用于嵌套在数组中的散列中的键值

标签 ruby-on-rails ruby html loops hash

我正在尝试在我的应用程序的每个新页面上生成随机引号。每个 random_quote 都是一个带有 :title、:quote 和 :author 键/值对的散列。这些散列嵌套在一个数组中,我使用 array#sample 方法随机选择一个并在页面上呈现。这是我目前正在使用的代码:

#module ApplicationHelper
def random_quote
  a = { :title  => "Ebola",
        :quote  => "Foobar",
        :author => "Bill O'Reily"}
  b = { :title  => "ISIS",
        :quote  => "Here I come to save the day!",
        :author => "Mighty Mouse"}

  random_quote_hash = [ a,b ].sample
end

#application view...
<% random_quote.each do |key, value| %>
  <h3><%= random_quote[key] = value %></h3>
<% end %>

此代码只是将 :title、:quote 和 :author 呈现为具有相同格式的 HTML 元素。 但是,我想对每个键的值应用不同的 HTML 格式...

eg :title = <h1 class="title">
   :quote = <h3 class="quote">
   :author = <h3 class="author">

看起来这应该 super 简单...... 如果我运行下面的代码,HTML 格式适用于每个键值...

<% random_quote.each do |key, value| %>
  <h1 class="title"><%= random_quote[:title].upcase %></h1>
  <h3 class="quote">"<%= random_quote[:quote] %>"</h3>
  <h3 class="author"><%= random_quote[:author] %></h3>
<% end >

但是,该行中引用的每个键都是通过 random_quote 方法随机采样的,因此不匹配,即标题与引用不匹配,也不与作者匹配,因为它们都来自不同的哈希值。

请帮助新手?谢谢!!

最佳答案

看来我把它搞得太难了…… 玩完这里:http://rubyfiddle.com/riddles/92897/7 我想到了:

#module ApplicationHelper
 def random_quote
   a = { :title  => "Ebola",
         :quote  => "Foobar",
         :author => "Bill O'Reily"}
   b = { :title  => "ISIS",
         :quote  => "Here I come to save the day!",
         :author => "Mighty Mouse"}

   quotes_array = [ a,b ]

   @random_quote_hash = quotes_array.sample
 end

#Application View
<% random_quote %>
<h3><%= @random_quote_hash[:title] %></h3>
<h1><%= @random_quote_hash[:quote] %></h1>
<p><%= @random_quote_hash[:author] %></p>

不过,我希望看到一种重构或更简洁的方法来做到这一点。谢谢!!

关于ruby-on-rails - 将不同的 HTML5 格式应用于嵌套在数组中的散列中的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26226437/

相关文章:

ruby-on-rails - Rails 应用程序在本地工作,但在部署到 Heroku 时不工作

ruby - 使用 RVM 和 ruby​​ 1.8.6 在 Lion 上安装 rspec-1.3.2 时出现问题

html - 使用 xpath 将解析后的 html 写入 R 中的文件

ruby-on-rails - 无法安装 gem capybara-webkit

ruby-on-rails - 在 Liquid Drop 中使用 Rails 的 stylesheet_link_tag 和 javascript_include_tag

ruby-on-rails - Rails - 使用 Slim 设置空白量

ruby - Ruby 是否提供了一种使用指定编码执行 File.read() 的方法?

ruby - 根据请求重新加载 rails.root/app/resources/*

html - 如何在 JIRA 5 中自定义 "Create Issue"弹出窗口?

javascript - 根据浏览器中显示的文本选择按钮元素