【发布时间】:2013-02-22 22:27:11
【问题描述】:
我有一个字典类,并希望能够使用“添加”方法将键(作为关键字)和值(作为定义)推送到空哈希中。我不明白如何在语法上编写它。我也包含了一个 RSPEC 文件。
红宝石:
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] = defintion 将 'word' 转换为符号时出现不同的错误
*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"*
【问题讨论】: