【发布时间】:2014-08-31 20:19:44
【问题描述】:
我有以下哈希:
{
"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"
}
在哪里可以看到它是散列的散列,有的有字符串值,有的有数组值。我想知道如何遍历这个数组,以便获得以下输出,例如 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>
到目前为止,我正在尝试遍历数组,因此遵循this answer (haml):
- object_details.each do |key, value|
%h3= key
- value.each do |v|
%p= v
作为第一项当然会立即失败,subtype 没有方法 each 因为它不是数组。
我会手动获取每个值,但如果值存在或不存在,哈希值可能会改变(例如,发布者或语言可能并不总是存在于哈希值中)
除了手动检查每个哈希是否存在之外,是否有一种智能的方法来遍历此哈希?
【问题讨论】:
-
您可以检查
value的类型,只有在它是哈希/数组时才进行迭代。否则只显示字符串。这样就足够了。 -
@matov 啊-我应该使用
.class吗?我试试看 -
你也可以使用
value.kind_of?(Array),或者只使用.class