Ruby 方法在类外工作,但在类内不工作

Ruby 方法在类外工作,但在类内不工作,ruby,Ruby,当我将“find”方法从类中拉出并测试它时,它似乎起作用,但由于某种原因,当它在类中时,它返回空。我不明白为什么 class Dictionary def entries @entries ||= {} end def add(entry) if entry.is_a?(String) == true @entries = {entry => nil} else @entries= entry end end

当我将“find”方法从类中拉出并测试它时,它似乎起作用,但由于某种原因,当它在类中时,它返回空。我不明白为什么

class Dictionary

  def entries
    @entries ||= {}
  end

  def add(entry)

    if entry.is_a?(String) == true
      @entries = {entry => nil}
    else
      @entries= entry
    end
  end

  def keywords
    @entries.keys.sort
  end

  def include?(word)
    entries.keys.include?(word)
  end

  def find(word)
    result = {}
    entries.each_pair do |key, value|
      if key =~ /#{word}/
        result[key] = value
      end
    end

    result
  end
end
它被卡在规范的这一部分

it 'finds multiple matches from a prefix and returns the entire entry (keyword + definition)' do
    @d.add('fish' => 'aquatic animal')
    @d.add('fiend' => 'wicked person')
    @d.add('great' => 'remarkable')
    @d.find('fi').should == {'fish' => 'aquatic animal', 'fiend' => 'wicked person'}
end
错误是说。。。 预期:{“鱼”=>“水生动物”、“恶魔”=>“恶人”} 获取:{}(使用==) 差别:@-1,3,1@@ -“恶魔”=>“邪恶的人” -“鱼”=>“水生动物”
#/11\u dictionary/dictionary\u spec.rb:67:in“block(2层)in>”

您的add方法将替换整个条目哈希,而不是实际添加条目。如果解决了这个问题,那么find方法应该会起作用

为了完整起见,以下是我将如何实现
add

def add(entry)
  if entry.is_a?(Hash)
    @entries.merge!(entry)
  else
    @entries[entry] = nil
  end
end

再举一个例子,你用这段代码试过了,发现它不起作用,它将帮助我们回溯。好的,谢谢,我添加了规范中卡住的部分。好的。。你犯了什么错误。你什么时候做这个测试的?在你的问题中张贴同样的内容。这些都是需要帮助你的。谢谢你,错误已经发布了。