下面是兩個相同的類,它們與運算符+
和<<
的區別不同。這些可以在注入方法中找到。在+
的情況下,測試通過,並在<<
其中一些失敗。爲什麼?Ruby中+和<<之間的區別
class Integer
ROMAN_NUMERALS = {
0 => '',
1 => 'I', 2 => 'II', 3 => 'III', 4 => 'IV', 5 => 'V', 6 => 'VI', 7 => 'VII', 8 => 'VIII', 9 => 'IX',
10 => 'X', 20 => 'XX', 30 => 'XXX', 40 => 'XL', 50 => 'L', 60 => 'LX', 70 => 'LXX', 80 => 'LXXX', 90 => 'XC',
100 => 'C', 200 => 'CC', 300 => 'CCC', 400 => 'CD', 500 => 'D', 600 => 'DC', 700 => 'DCC', 800 => 'DCCC', 900 => 'CM',
1000 => 'M', 2000 => 'MM', 3000 => 'MMM'
}
def to_roman
to_s.reverse.chars.each_with_index.inject("") do |roman_numeral, (character, index)|
ROMAN_NUMERALS[character.to_i * 10 ** index] << roman_numeral
end
end
end
我得到不同的結果,當我運行
class Integer
ROMAN_NUMERALS = {
0 => '',
1 => 'I', 2 => 'II', 3 => 'III', 4 => 'IV', 5 => 'V', 6 => 'VI', 7 => 'VII', 8 => 'VIII', 9 => 'IX',
10 => 'X', 20 => 'XX', 30 => 'XXX', 40 => 'XL', 50 => 'L', 60 => 'LX', 70 => 'LXX', 80 => 'LXXX', 90 => 'XC',
100 => 'C', 200 => 'CC', 300 => 'CCC', 400 => 'CD', 500 => 'D', 600 => 'DC', 700 => 'DCC', 800 => 'DCCC', 900 => 'CM',
1000 => 'M', 2000 => 'MM', 3000 => 'MMM'
}
def to_roman
to_s.reverse.chars.each_with_index.inject("") do |roman_numeral, (character, index)|
ROMAN_NUMERALS[character.to_i * 10 ** index] + roman_numeral
end
end
end
我使用的測試是低於
require 'minitest/autorun'
require_relative 'roman'
class RomanTest < MiniTest::Unit::TestCase
def test_1
assert_equal 'I', 1.to_roman
end
def test_2
assert_equal 'II', 2.to_roman
end
def test_3
assert_equal 'III', 3.to_roman
end
def test_4
assert_equal 'IV', 4.to_roman
end
def test_5
assert_equal 'V', 5.to_roman
end
def test_6
assert_equal 'VI', 6.to_roman
end
def test_9
assert_equal 'IX', 9.to_roman
end
def test_27
assert_equal 'XXVII', 27.to_roman
end
def test_48
assert_equal 'XLVIII', 48.to_roman
end
def test_59
assert_equal 'LIX', 59.to_roman
end
def test_93
assert_equal 'XCIII', 93.to_roman
end
def test_141
assert_equal 'CXLI', 141.to_roman
end
def test_163
assert_equal 'CLXIII', 163.to_roman
end
def test_402
assert_equal 'CDII', 402.to_roman
end
def test_575
assert_equal 'DLXXV', 575.to_roman
end
def test_911
assert_equal 'CMXI', 911.to_roman
end
def test_1024
assert_equal 'MXXIV', 1024.to_roman
end
def test_3000
assert_equal 'MMM', 3000.to_roman
end
end
看規格在一種情況下,但不是在其他的怎麼失敗的。我認爲這些意圖是以相同的方式工作。
現在你寫了一個完全不同的問題。 – Bonifacio2 2015-02-09 14:58:58
附註:這應該可能在末尾用'map.with_index' +'join'寫成。 – tokland 2015-02-09 15:43:45
你看過文檔嗎?那裏明確解釋了這些差異。 – 2015-02-09 17:37:29