0%

codewar-map.with_index

說明:這次沒有說明,就是按照以下邏輯去完成題目。

1
2
3
accum("abcd") -> "A-Bb-Ccc-Dddd"
accum("RqaEzty") -> "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
accum("cwAt") -> "C-Ww-Aaa-Tttt"

題目:

1
2
3
4
5
6
7
8
9
Test.describe("accum") do
Test.it("Basic tests") do
Test.assert_equals(accum("ZpglnRxqenU"), "Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu")
Test.assert_equals(accum("NyffsGeyylB"), "N-Yy-Fff-Ffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyy-Yyyyyyyyy-Llllllllll-Bbbbbbbbbbb")
Test.assert_equals(accum("MjtkuBovqrU"), "M-Jj-Ttt-Kkkk-Uuuuu-Bbbbbb-Ooooooo-Vvvvvvvv-Qqqqqqqqq-Rrrrrrrrrr-Uuuuuuuuuuu")
Test.assert_equals(accum("EvidjUnokmM"), "E-Vv-Iii-Dddd-Jjjjj-Uuuuuu-Nnnnnnn-Oooooooo-Kkkkkkkkk-Mmmmmmmmmm-Mmmmmmmmmmm")
Test.assert_equals(accum("HbideVbxncC"), "H-Bb-Iii-Dddd-Eeeee-Vvvvvv-Bbbbbbb-Xxxxxxxx-Nnnnnnnnn-Cccccccccc-Ccccccccccc")
end
end

解題:

  1. 先將題目的字串全部統一換成小寫

    1
    2
    Expected: "Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu", 
    instead got: "zpglnrxqenu"
  2. 用chars把每個字拆開,同時變成一個陣列

    1
    2
    Expected: "Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu", 
    instead got: ["z", "p", "g", "l", "n", "r", "x", "q", "e", "n", "u"]
  3. 用map.with_index方法對陣列每一個字元做事情,這邊用with_index可以抓到每個字元的索引值,然後讓他們倍數複製

    1
    2
    Expected: "Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu", 
    instead got: ["z", "pp", "ggg", "llll", "nnnnn", "rrrrrr", "xxxxxxx", "qqqqqqqq", "eeeeeeeee", "nnnnnnnnnn", "uuuuuuuuuuu"]
  4. 用capitalize讓每個元素的首字大寫

    1
    2
    Expected: "Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu", 
    instead got: ["Z", "Pp", "Ggg", "Llll", "Nnnnn", "Rrrrrr", "Xxxxxxx", "Qqqqqqqq", "Eeeeeeeee", "Nnnnnnnnnn", "Uuuuuuuuuuu"]
  5. 最後用join(‘-‘)把所有元素用’-‘符號穿在一起變成字串,得到最後結果

    1
    2
    3
    def accum(s)
    s.downcase.chars.map.with_index {|x, index| (x * (index + 1)).capitalize}.join('-')
    end