【问题标题】:How do I format the output of a hash in Ruby?如何格式化 Ruby 中的哈希输出?
【发布时间】:2013-11-13 10:40:17
【问题描述】:

我正在处理测试优先的 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

我还不能回答我自己的问题,所以这是我的解决方案:

第一次尝试:

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

它返回的大部分是正确的答案,但我不知道如何在单词的定义周围加上引号:

=> "[apple] 水果\n[fish] 水生动物\n[zebra] 非洲有条纹的陆地动物"

我尝试使用规范文档中的 %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

返回正确答案:

=> "[apple] \"fruit\"\n[fish] \"水生动物\"\n[zebra] \"非洲有条纹的陆地动物\""

【问题讨论】:

  • printable 到底是什么?
  • Printable 是一种以指定格式输出哈希的方法。

标签: ruby hash formatting


【解决方案1】:

你可以像这样迭代你的哈希

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

【讨论】:

    【解决方案2】:

    这个问题的目的是学习如何循环遍历哈希的键和值以及如何进行字符串插值。您应该能够通过使用以下提示来做到这一点:

    Hash#each

    string interpolation in ruby

    【讨论】:

      猜你喜欢
      • 2021-12-22
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 2015-06-02
      • 2014-01-25
      • 1970-01-01
      • 2018-09-24
      相关资源
      最近更新 更多