Charles Charles - 5 months ago 10
Ruby Question

How to make a string 1st letter caps, 2nd letter noncaps, 3rd letter caps, 4th letter noncaps...?

I want to change:

word = "Stackoverflow is awesome!"


into:

"StAcKoVeRfLoW Is aWeSoMe!"


I did:

result = ""
a = word.length
odd = (1..a).select(&:odd?)
even = (1..a).select(&:even?)
odd.each {|i| even.each {|b| result += word[b].to_s}}
result # => "akvrlwi wsm!akvrlwi wsm!akvrlwi wsm!akvrlwi wsm!akvrlwi wsm!akvrlwi wsm!akvrlwi wsm!akvrlwi wsm!akvrlwi wsm!akvrlwi wsm!akvrlwi wsm!akvrlwi wsm!akvrlwi wsm!"

Answer
"Stackoverflow is awesome!"
.gsub(/(.)(.)?/){$1.upcase + $2.to_s.downcase}
# => "StAcKoVeRfLoW Is aWeSoMe!"

"Stackoverflow is awesome!"
.gsub(/./).with_index{|s, i| i.even? ? s.upcase : s.downcase}
# => "StAcKoVeRfLoW Is aWeSoMe!"

"Stackoverflow is awesome!"
.gsub(/..?/, &:capitalize)
# => "StAcKoVeRfLoW Is aWeSoMe!"