2

我在 index.html.erb 文件中的代码发布在下面。当我在常规 ruby​​ 文件中进行测试时,我没有在输出中看到任何引号/括号。但是,当我在 erb 文件中使用相同的代码时,在浏览器中查看时,我会看到每个值周围显示引号和方括号。有没有办法解决这个问题?

---
title: Coast Guard Quiz
---

<%

seaman_recruit = {

    img: "<img src = 'images/USCG_SR.png'>",
    name: "Seaman Recruit",
    en_class: "Seaman",
    abbr: "SR",
}

seaman_apprentice = {
    img: "<img src = 'images/USCG_SA.png'>",
    name: "Seaman Apprentice",
    en_class: "Seaman",
    abbr: "SA",
}

seaman = {
    img:  "<img src = 'images/USCG_SM.png'>",
    name: "Seaman",
    en_class: "Seaman",
    abbr: "SN",
}

ranks = [seaman_recruit, seaman_apprentice, seaman]

ranks.shuffle!

current_rank = ranks.shuffle!.first

%>

<p><%= current_rank.values_at(:img) %></p>
<p class="bld"><%= current_rank.values_at(:name) %></p>
<p><%= current_rank.values_at(:en_class) %></p>
<p><%= current_rank.values_at(:abbr) %></p>
<p><%= current_rank.values_at(:title) %></p>
<p><%= current_rank.values_at(:paygrade) %></p>

例如,我看到这个:

[“(实际图像)”]

[“水手”]

[“水手”]

[“序列号”]

[“海员(姓氏)”]

[“E3”]

我想看看这个:

(实际图像)

水手

水手

序列号

海员(姓氏)

E3

4

1 回答 1

1

.values_at always returns an array. It will optionally accept multiple arguments and return the corresponding values from the hash. Since you're only giving a single argument, you get an array with one member.

You just want a standard lookup, either using bracket notation (current_rank[:title], etc) or fetch (current_rank.fetch(:title)). Fetch has the added option of defining a default value to prevent errors when the provided key is not present in the hash: current_rank.fetch(:key) { 'default value' }.

ERB is generally not the appropriate place to define data or behavior. Assuming you're using standalone erb templates (not backed by Rails or Sinatra), I would suggest a better option would be to define your templates separate from your ruby code, either in individual files or as strings in a standard ruby file. You can take a look at the documentation for some examples.

于 2013-02-17T01:10:10.653 回答