my code in index.html.erb file is posted below. When I tested in a regular ruby file, I did not see any quotes/brackets in output. However, when I use same code in erb file I see quotes and square brackets displayed around each value when viewed in browser. Is there any way to get around this?
---
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>
For example, I see this:
[“(actual image)”]
[“Seaman”]
[“Seaman”]
[“SN”]
[“Seaman (last name)”]
[“E3”]
And I want to see this:
(actual image)
Seaman
Seaman
SN
Seaman (last name)
E3
.values_atalways 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) orfetch(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.