簡體   English   中英

Ruby-如何遍歷具有數組和非數組值的哈希哈希

[英]Ruby - How to iterate over hash of hashes with array & non-array values

我有以下哈希值:

{
  "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>

到目前為止,我正在嘗試遍歷數組,因此請遵循以下答案 (haml):

- object_details.each do |key, value|
  %h3= key
  - value.each do |v|
    %p= v

當然,哪一個作為第一項subtype立即失敗,因為它不是數組,所以each subtype都沒有方法。

我會手動獲取每個值,但是如果值存在或不存在,則哈希值可能會發生變化(例如,哈希值中可能不總是存在發布者或語言)

除了手動檢查每個哈希的存在之外,是否有一種聰明的方法來遍歷此哈希?

正如@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

你近了。 嘗試這個:

- object_details.each do |key, value|
  %h3= key
  - if value.kind_of?(Array)
    -value.each do |v|
      %p= v
  - else
    %p= v
$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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM