Reputation: 796
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
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
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