Ruby - 如何使用array&amp ;;迭代哈希哈希值非数组值

时间:2014-07-10 12:41:45

标签: ruby arrays 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"
}

在哪里可以看到它是散列的散列,有些具有字符串值,而有些则具有数组值。我想知道如何迭代这个数组,以便我可以得到以下输出,例如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因为它不是数组而立即失败。

我会手动获取每个值,但如果值存在或不存在(例如,发布者或语言可能并不总是存在于哈希值中),则哈希值可能会发生变化

除了手动检查每个哈希的存在外,是否有一种智能方法来迭代这个哈希值?

3 个答案:

答案 0 :(得分:2)

正如@dax提到的那样,也许更清洁:

- object_details.each do |key, value|
  %h3= key
  %p= Array(value).join(', ')

我希望有帮助

更正!我没有看到嵌套的哈希。你可以做这样的事情(在帮手中)

   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

答案 1 :(得分:1)

你很亲密。试试这个:

- object_details.each do |key, value|
  %h3= key
  - if value.kind_of?(Array)
    -value.each do |v|
      %p= v
  - else
    %p= v

答案 2 :(得分:1)

$modifiedContent = []
def convert(hash)
   hash.each do |key, value|
      unless (value.kind_of?(Hash))
         unless (value.is_a? String and hash.first.first.eql? key and hash.first.last.eql? value)
            $modifiedContent << "<h3>#{key}</h3>"
            $modifiedContent << "<p>#{Array(value).join(', ')}</p>"
         else
            $modifiedContent << "<p>#{value}</p>"
         end
      else
         convert(value)
      end
      $modifiedContent << ""
   end
end

myHash = {
  "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"
}

convert(myHash)
puts $modifiedContent