Ruby Array.each_与_索引未按预期运行

Ruby Array.each_与_索引未按预期运行,ruby,Ruby,我重新定义了Arrayreplace,如下所示 require 'test/unit' class Array def replace (from, to) each_with_index do |e, i| self[i] = to if e = from end end end class TestDriver <Test::Unit::TestCase def test_replace book

我重新定义了Arrayreplace,如下所示

require 'test/unit'  
class Array  
  def replace (from, to)  
    each_with_index do |e, i|  
      self[i] = to if e = from  
    end  
  end  
end  

class TestDriver <Test::Unit::TestCase  
  def test_replace  
    book_topic = ['html', 'java', 'css']  
    book_topic.replace('java', 'ruby')  
    result_topic = ['html', 'ruby', 'css']  
    assert_equal book_topic, result_topic  
  end  
end  
当我运行这个测试用例时,它断言书的主题是['html','ruby','ruby']。我不知道这本书主题的结果。有人能告诉我为什么吗?

你在e==from中漏掉了一个

PS:我希望你知道像这样覆盖核心方法的利弊。

考虑使用map或map!而不是重写数组的replace方法

>> [1,2,3].map { |a| a == 1 ? 2 : a }
=> [2, 2, 3]

哦。我很傻。。。是的,我知道我正在重写一个核心类。非常感谢@madper根据你的评论,你可能应该把这个标记为答案。@CharlesCaldwell,当然。抱歉迟到了。当我把这个标记为答案时,它说我应该等9分钟。过了一会儿我就忘了。我想我得了老年痴呆症-
>> [1,2,3].map { |a| a == 1 ? 2 : a }
=> [2, 2, 3]