Ruby Challenge - efficiently change the last character of every word in a sentence to a capital

Posted by emson on Stack Overflow See other posts from Stack Overflow or by emson
Published on 2010-06-09T15:54:00Z Indexed on 2010/06/10 3:52 UTC
Read the original article Hit count: 227

Filed under:
|
|

Hi All I recently was challenged to write some Ruby code to change the last character of every word in a sentence into a capital. Such that the string:

  "script to convert the last letter of every word to a capital"
  becomes
  "scripT tO converT thE lasT letteR oF everY worD tO A capitaL"

This was my optimal solution however I'm sure you wizards have much better solutions and I would be really interested to hear them.

  "script to convert the last letter of every word to a capital".split.map{|w|w<<w.slice!(-1).chr.upcase}.join' '

For those interested as to what is going on here is an explanation.

split will split the sentence up into an array, the default delimiter is a space and with Ruby you don't need to use brackets here.

map the array from split is passed to map which opens a block and process each word (w) in the array. the block slice!(s) off the last character of the word and converts it to a chr (a character not ASCII code) and then capitalises upcase it. This character is now appended << to the word which is missing the sliced last letter. Finally the array of words is now join together with a ' ' to reform the sentence.

Enjoy

© Stack Overflow or respective owner

Related posts about ruby

Related posts about optimization