iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 4
0
自我挑戰組

自我挑戰 Ruby 刷題 30 天系列 第 4

用 TDD 刷 Codewars - Reverse words

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


題目

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"
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')

影片解題過程
Yes


解題:

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/


上一篇
換刷 Codewars - Find the next perfect square!
下一篇
要刷 1 題還是 2 題呢? 小孩子才做選擇,我全都要!!
系列文
自我挑戰 Ruby 刷題 30 天31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言