2013-04-28 91 views
0

我重新定義了Array#replace,如下所示。Array.each_with_index未按預期方式運行

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_topic['html', 'ruby', 'ruby']。我不知道book_topic的結果。誰能告訴我爲什麼?

回答

8

您錯過了=e == from。 PS:我希望你知道像這樣重寫核心方法的優點/缺點。

+0

ohhhhhh。我很愚蠢......是的,我知道我在壓倒核心課。非常非常感謝你! – madper 2013-04-28 15:33:51

+0

@madper根據您的評論,您應該將其標記爲答案。 – 2013-04-28 16:18:56

+0

@CharlesCaldwell,當然。對不起我遲到了。當我把這個標記爲答案時,它說我應該等9分鐘。過了一段時間我就忘記了。我想我得了阿爾茨海默病。 :-) – madper 2013-04-29 02:05:56

2

考慮使用mapmap!而不是重寫Array的替換方法。

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