Sunday, November 8, 2009

Code Kata 2 - Reverse words in a string using Ruby

Last time I posted the blog Code Kata - Reverse words in a string, in that blog I provided the java solution. Today I will try to solve this problem using Ruby.

Question: How to reverse words in a string?
For example, given a string "The quick brown fox jumped over the lazy dog", reversed string needs to be “dog lazy the over jumped fox brown quick The”.
And this time there is no memory constraint, we just focus on providing an elegant and concise code.

The algorithm has two steps:
1. First reverse the entire string by character
For example: "The quick brown fox jumped over the lazy dog" becomes
“god yzal eht revo depmuj xof nworb kciuq ehT”
2. Then reverse each word by character
For example: “god yzal eht revo depmuj xof nworb kciuq ehT” becomes
“dog lazy the over jumped fox brown quick The”

The ruby code would be:

The method reverse_string() will return an array instead of a string, but it does not matter here. You can see how easy to implement using Ruby compare to Java!

5 comments:

  1. another solution:

    puts s.split(/(\s+)/).reverse.join('')

    ReplyDelete
  2. And this:

    puts s.scan(/[\w]+/).reverse.join(" ")

    ReplyDelete
  3. My solution can be improved by:

    s.reverse.scan(/[\w]+/).collect { |w| w.reverse}.join(" ")

    ReplyDelete
  4. This website gives more solution:
    http://www.perlmonks.org/?displaytype=print;node_id=589260

    ReplyDelete