見習村14 - Simple Pig Latin

14 - Simple Pig Latin

Don’t say so much, just coding…

Instruction

Move the first letter of each word to the end of it, then add “ay” to the end of the word. Leave punctuation marks untouched.

Examples

1
2
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
pig_it('Hello world !') # elloHay orldway !

Ruby

Init

1
2
3
def pig_it text
# ...
end

Sample Testing

1
2
Test.assert_equals(pig_it('Pig latin is cool'),'igPay atinlay siay oolcay')
Test.assert_equals(pig_it('This is my string'),'hisTay siay ymay tringsay');

Javascript

Init

1
2
3
function pigIt(str){
//Code here
}

Sample Testing

1
2
Test.assertEquals(pigIt('Pig latin is cool'),'igPay atinlay siay oolcay')
Test.assertEquals(pigIt('This is my string'),'hisTay siay ymay tringsay')

Thinking

想法(1): 第一個想法就是 regex 直接切兩群,然後把第一群接到第二群後面再加上 ay 的字
想法(2): 不過畢竟 regex 如果像我ㄧ樣爛,就想說可以繞開看看,把第一個字組在 slice 掉第一個字後,然後再加上 ay 也是可以(傳入值有可能有驚嘆號!問號?

https://ithelp.ithome.com.tw/upload/images/20200929/201208261punaj8vOx.jpg
圖片來源:Unsplash Glenn Carstens-Peters

Hint & Reference

Solution

Ruby

1
2
3
4
# Solution 1
def pig_it text
text.gsub(/(\w)(\w+)*/, '\2\1ay')
end

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
// Solution 1
function pigIt(str){
let Array = [];
let split = str.split(' ');
for (i = 0; i < split.length; i++) {
if (split[i] != '?' && split[i] != '!') {
Array.push(split[i].slice(1) + split[i].charAt(0) + 'ay');
} else {
Array.push(split[i]);
}
}
return Array.join(' ');
}