【问题标题】:Method works outside of Class, but not inside方法在类外有效,但在类内无效
【发布时间】:2014-06-10 10:21:36
【问题描述】:

当我将“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_dictionary/dictionary_spec.rb:67:in 'block (2 levels) in >'

【问题讨论】:

  • 把例子也放上去,你用这段代码试过了,发现不行,它会帮助我们回溯。
  • 好的,谢谢,我添加了规范中卡住的部分。
  • 好的.. 你遇到了什么错误。当你运行这个测试?在您的问题中发布相同的内容。这些都需要帮助你。
  • 谢谢,错误已发布。

标签: ruby


【解决方案1】:

您的 add 方法会替换整个条目哈希,而不是实际添加条目。修复这个问题,find 方法应该可以工作了。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 2019-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多