你必須很努力

用 TDD 刷 Codewars - Reverse words

2019/09/13
字數統計: 209閱讀時間: 1 min

昨天刷 Codewars Lv8 題目
覺得不過癮
這次改以 TDD 刷 Codewars Lv7 題目
花了些時間講解如何設定 snippetRSpec
snippet 做得好,省時又省力外,還能避免常打的語法打錯字
RSpec 寫得好,生活沒煩惱 XD


題目

1
2
3
4
5
Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.

Examples
"This is an example!" ==> "sihT si na !elpmaxe"
"double spaces" ==> "elbuod secaps"

1
2
3
4
5
6
7
8
9
def reverse_words(str)
# Go for it
end

Sample Tests:
Test.assert_equals(reverse_words('The quick brown fox jumps over the lazy dog.'), 'ehT kciuq nworb xof spmuj revo eht yzal .god')
Test.assert_equals(reverse_words('apple'), 'elppa')
Test.assert_equals(reverse_words('a b c d'), 'a b c d')
Test.assert_equals(reverse_words('double spaced words'), 'elbuod decaps sdrow')


影片解題過程


解題:

1
2
3
4
def reverse_words(str)
return str.split.map{ |x| x.reverse }.join' ' if str.scan(/ /) == []
str.split.map{ |x| x.reverse }.join' '
end

本文同步發布於 小菜的 Blog https://riverye.com/

原文連結:https://riverye.com/2019/09/13/用-TDD-刷-Codewars-Reverse-words/

發表日期:2019-09-13

更新日期:2022-12-21

CATALOG