简体   繁体   English

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

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

I am going through the test-first Ruby problems and am working on problem 11, dictionary. 我正在经历测试优先的Ruby问题,并且正在研究问题11,字典。 The final test in the spec file requests that I print all of the keys and values of the hash (words and their definitions) in a specific format. 规格文件中的最终测试要求我以特定格式打印哈希的所有键和值(单词及其定义)。

How do I do this? 我该怎么做呢? Is there is a specific name for this type of output? 这种输出类型是否有特定名称? I can't understand how to get the output to look like this or what all of the extra symbols mean. 我不明白如何使输出看起来像这样或所有其他符号的含义。

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

When I run the method and just return the hash normally it says this: 当我运行该方法并正常返回哈希值时,它说:

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

Update 6:38pm pacific time 太平洋时间更新6:38 pm

I can't answer my own questions yet so here is my solution: 我还不能回答自己的问题,所以这是我的解决方案:

First try: 第一次尝试:

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

It returned mostly the right answer but I couldn't figure out how to get quotes around the definitions of the words: 它基本上返回了正确的答案,但我不知道如何获得围绕单词定义的引号:

=> "[apple] fruit\\n[fish] aquatic animal\\n[zebra] African land animal with stripes" =>“ [苹果]水果\\ n [鱼]水生动物\\ n [斑马]有条纹的非洲陆地动物”

I tried using the %Q{ } wrapper from the spec doc and that solved the quotation mark problem. 我尝试使用规格文档中的%Q {}包装器,从而解决了引号问题。 Then I reworked my notation of the variables and such, as seen below. 然后,我对变量等的表示进行了重新设计,如下所示。

This is the answer I finally came up with: 这是我最终想出的答案:

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

It returns the correct answer: 它返回正确的答案:

=> "[apple] \\"fruit\\"\\n[fish] \\"aquatic animal\\"\\n[zebra] \\"African land animal with stripes\\"" =>“ [苹果] \\”水果\\“ \\ n [鱼] \\”水生动物\\“ \\ n [斑马] \\”有条纹的非洲陆地动物\\“”

You can iterate over your hash like so 您可以像这样遍历哈希

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

The purpose of this problem is to learn about how to loop through keys and values of a hash and how to do string interpolation. 这个问题的目的是学习如何遍历散列的键和值以及如何进行字符串插值。 You should be able to do this by using following hints: 通过使用以下提示,您应该能够做到这一点:

Hash#each 哈希值

string interpolation in ruby 红宝石中的字符串插值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM