private method `select' called for nil:NilClass (NoMethodError)

class, ruby

Solution

You are never calling the method `keywords`, and thus, you are never executing the code that populates `@keywords` with data. It remains nil.

Problem

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. I get the following error private method `select' called for nil:NilClass (NoMethodError) when I type in the following line: ``` 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? ``` 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 ```

Original source