實作accumulate操作:給定一個集合,以及一個要對集合中每個元素執行的操作,它會回傳一個新的集合,其中包含將該操作套用到輸入集合中每個元素的結果。
給定這組數字:
以及這個操作:
x => x * x)你的程式碼應該要能產生這組平方數:
請查看測試套件,了解預期的函式簽名。
別去碰標準函式庫提供的那個 collect/map/fmap 之類的功能! 請改用其他基本工具,自己解決這一題。
在為泛用的 Enumerable 定義方法時,通常會呼叫 #to_enum,以防沒有傳入區塊。
以下是你可以額外加入的測試:
def test_accumulate_when_block_is_deferred
skip
accumulate_enumerator = [1, 2, 3].accumulate
accumulated_result = accumulate_enumerator.map do |number|
number * number
end
assert_equal [1, 4, 9], accumulated_result
end