我正在尝试在我的应用程序的每个新页面上生成随机引号。每个 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/