簡體   English   中英

如何在Ruby中格式化哈希的輸出?

[英]How do I format the output of a hash in Ruby?

我正在經歷測試優先的Ruby問題,並且正在研究問題11,字典。 規格文件中的最終測試要求我以特定格式打印哈希的所有鍵和值(單詞及其定義)。

我該怎么做呢? 這種輸出類型是否有特定名稱? 我不明白如何使輸出看起來像這樣或所有其他符號的含義。

it 'can produce printable output like so: [keyword] "definition"' do
  @d.add('zebra' => 'African land animal with stripes')
  @d.add('fish' => 'aquatic animal')
  @d.add('apple' => 'fruit')
  @d.printable.should == %Q{[apple] "fruit"\n[fish] "aquatic animal"\n[zebra] "African land animal with stripes"}
end

當我運行該方法並正常返回哈希值時,它說:

expected: "[apple] \"fruit\"\n[fish] \"aquatic animal\"\n[zebra] \"African land animal with stripes\""

太平洋時間更新6:38 pm

我還不能回答自己的問題,所以這是我的解決方案:

第一次嘗試:

def printable
    print_string = ""
    @hash1.sort.each do |k,v|
        print_string = print_string + "[" + k + "]" + " " + "#{v.to_s}" + "\n"
    end
    print_string.chomp
end

它基本上返回了正確的答案,但我不知道如何獲得圍繞單詞定義的引號:

=>“ [蘋果]水果\\ n [魚]水生動物\\ n [斑馬]有條紋的非洲陸地動物”

我嘗試使用規格文檔中的%Q {}包裝器,從而解決了引號問題。 然后,我對變量等的表示進行了重新設計,如下所示。

這是我最終想出的答案:

def printable
  printable_string = ""
  @hash1.sort.each do |k,v|
    printable_string = printable_string + %Q{[#{k}] "#{v}"\n}
  end
  return printable_string.chomp
end

它返回正確的答案:

=>“ [蘋果] \\”水果\\“ \\ n [魚] \\”水生動物\\“ \\ n [斑馬] \\”有條紋的非洲陸地動物\\“”

您可以像這樣遍歷哈希

d.each do |key,value|
    puts key
    puts value
end

這個問題的目的是學習如何遍歷散列的鍵和值以及如何進行字符串插值。 通過使用以下提示,您應該能夠做到這一點:

哈希值

紅寶石中的字符串插值

暫無
暫無

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

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