在Ruby中将每个单词的每个n个字符大写

Ser*_*rgi 2 ruby string uppercase

我需要为字符串中的每个单词大写每个“第n个”字符(在此示例中,第4个字符的倍数,因此字符4、8、12等)。

我想出了以下代码(我知道不是很优雅!),但是它仅适用于which length < 8

'capitalize every fourth character in this string'.split(' ').map do |word|
  word.split('').map.with_index do |l,idx|
  idx % 3 == 0 && idx > 0 ? word[idx].upcase : l 
  end 
  .join('')
end 
.flatten.join(' ')
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我如何将长度> 8的单词中的第4个字符大写吗?

谢谢!

Igo*_*dov 5

作为选择,您可以仅通过按索引访问字符来修改字符串中的第n个字符(如果存在):

'capitalizinga every fourth character in this string'.split(' ').map do |word|
  (3..word.length).step(4) do |x|
    c = word[x]
    word[x] = c.upcase if c
  end
  word
end.join(' ')

# capItalIzinGa eveRy fouRth chaRactEr in thiS strIng
Run Code Online (Sandbox Code Playgroud)

这是使用的方法步骤Range类,因此可以计算每个第四个索引:3、7、11等。


Car*_*and 5

str = 'capitalize every fourth character in this string'

idx = 0
str.gsub(/./) do |c|
  case c
  when ' '
    idx = 0
    c
  else
    idx += 1
    (idx % 4).zero? ? c.upcase : c
  end
end
  #=> "capItalIze eveRy fouRth chaRactEr in thiS strIng"
Run Code Online (Sandbox Code Playgroud)

  • 好的答案,我从未见过.gsub()被以这种方式使用。 (2认同)