2013-02-13 21 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"}