0

我重新定义Array#replace如下。

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  

当我运行该测试用例时,它断言book_topicis ['html', 'ruby', 'ruby']。我不知道book_topic. 谁能告诉我为什么?

4

2 回答 2

8

You missed an = in e == from.

self[i] = to if e == from

PS: I hope you know the pros/cons of overriding core methods like this.

于 2013-04-28T15:31:34.983 回答
2

考虑使用mapormap!而不是覆盖 Array 的 replace 方法。

>> [1,2,3].map { |a| a == 1 ? 2 : a }
=> [2, 2, 3]
于 2013-04-28T15:36:52.193 回答