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:
def reverse_string(s)
s.reverse().scan(/[\w]+/).collect { |w| w.reverse()}
end
r = reverse_string("The quick brown fox jumped over the lazy dog")
puts r
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!
Subscribe to:
Post Comments (Atom)
another solution:
ReplyDeleteputs s.split(/(\s+)/).reverse.join('')
My solution can be improved by:
ReplyDeletes.reverse.scan(/[\w]+/).collect { |w| w.reverse}.join(" ")
And this:
ReplyDeleteputs s.scan(/[\w]+/).reverse.join(" ")
This website gives more solution:
ReplyDeletehttp://www.perlmonks.org/?displaytype=print;node_id=589260