简体   繁体   中英

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. 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

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"

I tried using the %Q{ } wrapper from the spec doc and that solved the quotation mark problem. 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\\""

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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