I have an array of hashes in the format
albums = [ {name: "Sgt. Pepper's Lonely Hearts Club Band", year: "1967" },
{ name: "Are You Experienced?", year: "1967" }
]
etc..
I am trying to insert this output into a string that then needs to be inserted into html. I currently have this
def convert_to_html albums
string_before =
"<html>
<head>
<title>\"Rolling Stone's ....\"</title>
</head>
<body>
<table>\n" +
albums.each do |x|
"name is: #{x.values[0]} year is: #{x.values[1]}"
end + "
</table>
</body>
</html>"
end
I know that this probably isn’t the best way to get the values but I can’t figure out any other way, but my major problem is that when I try this I get this error:
[2013-01-27 00:16:20] ERROR TypeError: can't convert Array into String
albums.rb:72:in `+'
albums.rb:72:in `convert_to_html'
albums.rb:28:in `block in render_list'
albums.rb:26:in `open'
albums.rb:26:in `render_list'
albums.rb:9:in `call'
Is there any way to insert the values from each hash side by side into the string?
P.S. I used name and year for readability. I know #{x.values[0]} #{x.values[1]} is the correct way to format this.
This is simple code showing how to do it:
Which outputs:
In real life I’d use ERB or HAML to generate the HTML. They’re great templating tools.
Other ways of writing:
Are:
or:
I don’t recommend using
album.valuesby itself because it relies on the order of insertion into thealbumhash. In the future, if you modify the hash by putting something into it in a different order while maintaining the code, thevaluesorder will change, breaking it in a way that might not be obvious.Instead, use one of these ways of accessing the values to always explicitely get the value associated with the key. That’s part of programming defensively.