2013-02-13 49 views
0

我很难找出这个挑战。以下是我有:rspec Ruby要插入到Hash的方法

class Dictionary 
attr_accessor :entries 

def initialize 
    @x = Hash.new 
end 

def entries 
    @x 
end 

def add(hash) 
    @x.merge!(hash) 
end 

end 

@d=Dictionary.new 
@d.add('fish' => 'aquatic animal') 
puts @d.entries 

我越来越=> “fishaquatic动物”

我希望得到=> { '鱼'=> '水生动物'}

回答

2

to_sHash的行为低于理想一些Ruby版本。尝试puts @d.entries.inspect

更新:

下面的代码对我的作品(红宝石1.9.3和RSpec 2.12.0):

class Dictionary  
    def initialize 
    @x = Hash.new 
    end 

    def entries 
    @x 
    end 

    def add(hash) 
    @x.merge!(hash) 
    end 
end 

describe Dictionary do 
    before do 
    @d = Dictionary.new 
    end 

    it 'can add whole entries with keyword and definition' do 
    @d.add('fish' => 'aquatic animal') 
    @d.entries.should == {'fish' => 'aquatic animal'} 
    end 
end 
+0

这样做!只有这是...我试图满足rpec代码...他们有'@ d.add('fish'=>'aquatic animal')'......任何想法?谢谢@Levi – 2013-02-13 01:47:01

+0

我用一个适用于我的示例测试更新了答案。你有不同的行为吗? – 2013-02-13 02:02:27

+0

这一个工作..谢谢!!我看到的唯一区别是你的代码没有'attr_accessor:entries',你知道为什么会导致不同的结果吗? – 2013-02-13 03:09:13

0

正如所写的,您的代码当前将@x设置为一个新的空Hash,然后每次调用entries方法时将其返回。

尝试移动该设置代码为初始化方法:

class Dictionary 
    attr_reader :entries 

    def initialize 
     @entries = Hash.new 
    end 

    def add(hash) 
     @entries.merge!(hash) 
    end 
end 
+0

感谢伟大的指针....试图运行...还是得到错误“错误的参数数量” – 2013-02-13 00:45:26

+0

当测试调用'@ d.add'时,你会得到那个错误吗? – 2013-02-13 00:46:50

+0

我在这里得到它:@ d.add('fish'=>'水生动物') @ d.entries.should == {'fish'=>'水生动物'} – 2013-02-13 00:50:49

0

它看起来像我的RSpec的代码有点怪异。第二个测试执行一个条目方法,并且条目方法将实例变量@x重置为空白。因此,最好将实例变量作为attr_reader添加,然后在创建新字典对象时对其进行初始化。因此,这将是这个样子

class Dictionary 
    attr_reader @x 

    def initialize 
     @x = Hash.new 
    end 

    def add(hash) 
     @x.merge!(hash) 
    end 
end 

和测试会是这样

@d.add(fish: "aquatic animal") 
@d.x.should == {'fish' => "aquatic animal"}