[英]can I use hash.each even if i'm passing only a string key? Dictionary without definition
This is the error I'm getting. 这是我得到的错误。 I need to pass a string key to a method that usually accepts string key and string symbol combo 我需要将字符串键传递给通常接受字符串键和字符串符号组合的方法
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)>'
This is the following spec. 这是以下规格。 the @d.add('fish') passes a string without definition. @ d.add('fish')传递没有定义的字符串。 require 'dictionary' 需要“字典”
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
my code: 我的代码:
I think my definition.each is where it goes wrong. 我认为我的定义。每个地方都出了问题。 From what I understand each goes through the array or hash in this example but only has one value so it doesn't know how to loop through it? 据我了解,在此示例中,每个数组或哈希都经过数组或哈希,但只有一个值,因此不知道如何遍历数组或哈希? So I thought about setting a default nil value for meaning and word but it doesn't accept it and comes with different errors. 因此,我考虑过为含义和单词设置默认的nil值,但它不接受它,并且会出现不同的错误。
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
Thanks for you help in advance! 感谢您的帮助!
You're trying to call each
on a String
in @d.add('fish')
, which isn't allowed. 您尝试在@d.add('fish')
的String
上调用each
String
,这是不允许的。 You could just add the following line above definition.each do |word, meaning|
您可以只在definition.each do |word, meaning|
上方添加以下行definition.each do |word, meaning|
: :
definition = { definition => nil } unless definition.is_a? Hash
although this could have unexpected consequences if you are passing different kinds of objects to add
. 虽然这可能有意想不到的后果,如果你逝去的不同类型的对象的add
。
My code is rough.. This works too. 我的代码很粗糙。
def add(hash) def add(哈希)
if (hash.is_a? Hash) 如果(hash.is_a?哈希)
@d=hash
else 其他
@d = {hash => nil}
end 结束
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.