0

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?

2 Answers 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.

Sign up to request clarification or add additional context in comments.

3 Comments

ohhhhhh. I'm foolish... Yes, I know I'm overriding a core class. Thank you very very much!
@madper Based on your comment, you should probably mark this as the answer.
@CharlesCaldwell, Sure. Sorry for late. When I mark this as answer, it said I should wait 9minutes. And I forget it after a while. I think I got Alzheimerdisease. :-)
2

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.