[英]private method `select' called for nil:NilClass (NoMethodError)
I am new to ruby and would love some help please :) 我是红宝石的新手,请帮忙:)
I fixed the error in my ruby code, but I'm confused as to WHY the fix works. 我已在我的ruby代码中修复了该错误,但是我对为什么该修复程序感到困惑。
I get the following error private method `select' called for nil:NilClass (NoMethodError) when I type in the following line: 当我在以下行中键入时,得到以下错误私有方法`select',调用nil:NilClass(NoMethodError) :
scanned = @keywords.select { |key| key.match(word) }
, which is located within the following method: ,位于以下方法中:
def find(word)
return {} unless @entries.any?
scanned = @keywords.select { |key| key.match(word) }
found ={}
if scanned.any?
scanned.each do |x| found.merge!( { x => @entries[x] } )
end
else
{}
end
found
end
,yet this error goes away if I replace the erroneous line above with the following: ,但是如果我用以下内容替换上面的错误行,此错误就消失了:
scanned = @entries.keys.sort.select { |key| key.match(word) }
I define @keywords as @keywords = @entries.keys.sort in the class structure below... Why can't I use '.select' on @keywords yet I can use it on @keywords' contents? 我在下面的类结构中将@keywords定义为@keywords = @ entries.keys.sort ... 为什么不能在@keywords上使用'.select',但可以在@keywords的内容上使用它呢?
class Dictionary
def initialize
@entries = {}
end
def entries
@entries
end
def add(entry)
@entries = entry.is_a?(Hash) ? @entries.merge!(entry) : @entries.merge!( {entry => nil} )
end
def keywords
@keywords = @entries.keys.sort
end
def include?(keyword)
@entries.keys.include?(keyword)
end
def find(word)
return {} unless @entries.any?
scanned = @keywords.select { |key| key.match(word) }
found ={}
if scanned.any?
scanned.each do |x| found.merge!( { x => @entries[x] } )
end
else
{}
end
found
end
def printable
printable = @entries.sort.map do |key, value| %Q{[#{key}] "#{value}"}
end
printable.join("\n")
end
end
You are never calling the method keywords
, and thus, you are never executing the code that populates @keywords
with data. 您永远不会调用method
keywords
,因此,您永远不会执行用数据填充@keywords
的代码。 It remains nil. 它仍然为零。
@keywords will remain nil until you call the method keywords
, which will initialize @keywords to be the sorted entry keys. @keywords将保持为零,直到您调用method
keywords
,该方法会将@keywords初始化为已排序的输入键。
It looks like you're calling find
on a dictionary object without first calling keywords. 看起来您是在没有首先调用关键字的情况下在字典对象上调用
find
。 This would result in a nil value for @keywords. 这将导致@keywords的值为零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.