這是我收到的錯誤。我需要一個字符串鍵傳遞給通常接受字符串鍵和字符串符號組合即使我僅傳遞一個字符串鍵,我可以使用hash.each嗎?沒有定義的字典
Dictionary
is empty when created`
can add whole entries with keyword and definition
add keywords (without definition) (FAILED - 1)
Failures:
1) Dictionary add keywords (without definition)
**Failure/Error: @d.add('fish')
NoMethodError:
undefined method `each' for "fish":String
# ./11_dictionary/dictionary.rb:9:in `add'**
# ./11_dictionary/dictionary_spec.rb:27:in `block (2 levels) in <top (required)>'
這是以下規格的方法。 @ d.add('fish')傳遞一個沒有定義的字符串。 需要 '字典'
describe Dictionary do
before do
@d = Dictionary.new
end
it 'is empty when created' do
@d.entries.should == {}
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
it 'add keywords (without definition)' do
@d.add('fish')
@d.entries.should == {'fish' => nil}
@d.keywords.should == ['fish']
end
我的代碼:
我覺得我definition.each是哪裏出了問題。從我所瞭解的每一個在這個例子中通過數組或哈希值,但只有一個值,所以它不知道如何循環它?所以我想過爲意義和單詞設置一個默認的零值,但它不接受它,並帶有不同的錯誤。
class Dictionary
attr_accessor :keywords, :entries
def initialize
@entries = {}
end
def add(definition)
definition.each do |word, meaning|
@entries[word] = meaning
end
end
def keywords
@entries.keys.sort
end
def include?(key)
@entries.key?(key)
end
def find(query)
@entries.select { |word, definition| word.scan(query).join == query}
end
def entries
@entries
end
end
感謝您提前幫忙!