0

I'm trying to pass an rspec test as below:

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
end

I'm getting this error:

  expected: "[apple] \"fruit\"\n[fish] \"aquatic animal\"\n[zebra] \"African land animal with stripes\""
            got: {"apple"=>"fruit", "fish"=>"aquatic animal", "zebra"=>"African land animal with stripes"} (using ==)

My code is as follows, I realize that the sort_by method results in an array, but I'm stuck on how to make this pass.

def printable
    sorted = Hash[@entries.sort_by{|keyword, definition| keyword}]
    sorted.each do |keyword, definition| 
        print "[#{keyword}] \"#{definition}\"\n"
    end
 end

Would appreciate your input on how to make this more efficient/pass.

1 Answer 1

0

Edited following Uri Agassi's comment.

def printable
  @entries.sort.map{|k, v| "[#{k}] \"#{v}\""}.join($/)
end
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks @sawa. Is there any way you could explain what I was doing wrong, and the .join($/) part?
You were using each, which returns the original object you had, which is the hash. As for join, that turns an array into a single string.
You don't need the &:first - natural ordering starts with the first element, using the rest of the array as a tie-breaker - @entries.sort should be enough
Thanks for the insight @UriAgassi. Quick question, is the "$/" a regular expression? What does it stand for?
@anjoob $/ is the system's new-line - type p $/ in irb and see for yourself