我有一个字典类,希望能够使用“添加”方法将键(作为关键字)和值(作为定义)推送到空哈希中。我不明白如何从语法上写出来。我也包含了一个 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
规格:
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
任何帮助表示赞赏。谢谢!
更新: 感谢 Dave Newton 的回复。我使用了您的代码并收到此错误:
错误:
*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"*