madper
madper

Reputation: 796

Array.each_with_index doesn't run as expected

I redefined Array#replace like follows.

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  

When I run that test case, it asserts the book_topic is ['html', 'ruby', 'ruby']. I have no idea about the result of book_topic. Can anyone tell me why?

Upvotes: 0

Views: 144

Answers (2)

Denis de Bernardy
Denis de Bernardy

Reputation: 78561

Consider using map or map! instead of overriding Array's replace method.

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

Upvotes: 2

Dogbert
Dogbert

Reputation: 222398

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.

Upvotes: 8

Related Questions