将每个单词的第一个字母附加到结尾

时间:2017-08-25 09:51:15

标签: ruby

对于每个单词,我试图将单词的第一个字母移到单词的末尾。例如,

  • "this is an example" ----> "hist si na xamplee"

我用一个词来实现这一点,例如,

x = "hello"
x << x.split("").shift # => "elloh"

3 个答案:

答案 0 :(得分:6)

"this is an example".gsub(/(\S)(\S+)/, '\2\1')
# => "hist si na xamplee"

答案 1 :(得分:4)

'this is an example'.split.map { |word| word.chars.rotate.join }.join(' ')
#=> "hist si na xamplee"

参考文献:

答案 2 :(得分:0)

 "It was the best of times, it was the worst of times".
   gsub(/[\p{Alpha}']+/) {  |s| s[1..-1]<<s[0]}
   #=> "tI asw het estb fo imest, ti asw het orstw fo imest"