Rspec测试未通过。 Sort_by数组以哈希

时间:2014-05-15 04:53:49

标签: ruby rspec

我试图通过如下的rspec测试:

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

我收到此错误:

  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 ==)

我的代码如下,我意识到sort_by方法会产生一个数组,但我仍然坚持如何进行传递。

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

非常感谢您就如何提高效率/传递提出意见。

1 个答案:

答案 0 :(得分:0)

按照Uri Agassi的评论编辑。

def printable
  @entries.sort.map{|k, v| "[#{k}] \"#{v}\""}.join($/)
end