[SOLVED] Capitalize every nth character of each word in a string in Ruby

Issue

I need to capitalize every ‘nth’ character for each word in a string (every multiple of 4-th character in this example, so character 4, 8, 12 etc).

I came up with the code below (not very elegant I know!) but it only works for words 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(' ')

Anybody could show me how to capitalize every 4th character in words which length > 8?

Thanks!

Solution

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"

Answered By – Cary Swoveland

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *