Ruby の場合
Ruby1.9.3
replace.rb
def replace(array, from, to) array.each_with_index do |e, i| array[i] = to if e == from end end
test_replace.rb
require 'minitest/unit' load 'replace.rb' MiniTest::Unit.autorun class ReplaceTest < MiniTest::Unit::TestCase def test_replace book_topics = ['html', 'java', 'css'] replace(book_topics, 'java', 'ruby') expected = ['html', 'ruby', 'css'] assert_equal expected, book_topics end end
shell
$ ruby test_replace.rb -v Run options: -v --seed 60141 # Running tests: ReplaceTest#test_replace = 0.00 s = . Finished tests in 0.000441s, 2267.5737 tests/s, 2267.5737 assertions/s. 1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
これでよいのかな?
Pythonの場合
お手軽簡単にdoctestで
Python2.7
hoge.py
def rep(array, from_str, to_str): """ >>> book_topics = ['html', 'java', 'css'] >>> rep(book_topics, 'java', 'ruby') >>> expected = ['html', 'ruby', 'css'] >>> assert expected == book_topics """ for i, e in enumerate(array): if e == from_str: array[i] = to_str if __name__ == '__main__': import doctest doctest.testmod()
shell
$ python hoge.py -v Trying: book_topics = ['html', 'java', 'css'] Expecting nothing ok Trying: rep(book_topics, 'java', 'ruby') Expecting nothing ok Trying: expected = ['html', 'ruby', 'css'] Expecting nothing ok Trying: assert expected == book_topics Expecting nothing ok 1 items had no tests: __main__ 1 items passed all tests: 4 tests in __main__.rep 4 tests in 2 items. 4 passed and 0 failed. Test passed.
こんな感じか?