我有一个字典类,希望能够通过'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"*