我有一個字典類,希望能夠通過'add'方法將鍵(作爲關鍵字)和值(作爲定義)推送到空的哈希中。我不明白如何在語法上編寫它。我也包含了一個RSPEC文件。如何將鍵和值推入空的哈希w/Ruby?
紅寶石:
class Dictionary
attr_accessor :keyword, :definition
def entries
@hash = {}
end
def add(options)
options.map do |keyword, definition|
@hash[keyword.to_sym] = definition
end
end
end
Rspec的:
require 'dictionary'
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'}
@d.keywords.should == ['fish']
end
任何幫助表示讚賞。謝謝!
更新: 謝謝戴夫牛頓的回覆。我用你的代碼,並得到這個錯誤:
錯誤:
*Failure/Error: @d.keywords.should == ['fish']
NoMethodError:
undefined method `keywords' for #<Dictionary:0x007fb0c31bd458
@hash={"fish"=>"aquatic animal"}>*
我得到一個不同的錯誤,當我使用@hash [word.to_sym] =確定指標
轉換「字」成符號*Failure/Error: @d.entries.should == {'fish' => 'aquatic animal'}
expected: {"fish"=>"aquatic animal"}
got: {:fish=>"aquatic animal"} (using ==)
Diff:
@@ -1,2 +1,2 @@
-"fish" => "aquatic animal"
+:fish => "aquatic animal"*