Ruby - How to iterate hashes hash with array & amp; Values outside table
source link: https://www.codesd.com/item/ruby-how-to-iterate-hashes-hash-with-array-values-outside-table.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Ruby - How to iterate hashes hash with array & amp; Values outside table
I have the following hash:
{
"subtype"=>"example subtype",
"contributors"=> {
"Concept"=>["Example Contributor", "Example Contributor"],
"Editor"=>["Example Contributor", "Example Contributor"],
"Photographer"=>["Example"]
},
"publisher"=>"Example Publisher",
"language"=>"Example Language",
"dimensions"=>"Example Dimensions"
}
Where one can see that it is a hash of hashes, and some have string values and some have array values. I was wondering how I can iterate through this array so that I could have the following output, for example html:
<h3>example subtype</h3>
<h3>Concept</h3>
<p>Example Contributor, Example Contributor</p>
<h3>Editor</h3>
<p>Example Contributor, Example Contributor</p>
<h3>Photographer</h3>
<p>Example</p>
<h3>Publisher</h3>
<p>Example Publisher</p>
<h3>Language</h3>
<p>Example Language</p>
<h3>Dimensions</h3>
<p>Example Dimensions</p>
So far, I am trying to iterate through the array so following this answer (haml):
- object_details.each do |key, value|
%h3= key
- value.each do |v|
%p= v
Which of course fails immediately as the first item, subtype
has no method each
as it is not an array.
I would take each value manually, but the hash may change if values are present or absent (for example, publisher or language may not always be present in the hash)
Is there a smart way to iterate through this hash other than checking for the presence of each hash manually?
As @dax mention, and maybe cleaner like:
- object_details.each do |key, value|
%h3= key
%p= Array(value).join(', ')
I hope that helps
Correction! I didn't see the nested Hash. You can do something like this(in a helper)
def headers_and_paragraphs(hash)
hash.each do |k, v|
if v.kind_of?(Hash)
headers_and_paragraphs(v)
else
puts "h3: #{k}" # Replace that with content_tag or something similar
puts "p: #{Array(v).join(', ')}" # Replace that with content_tag or something similar
end
end
end
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK