Reputation: 47472
I want to reverse all the words in a string such that
For Ex:- When my string is "How Are You" it should return "woH erA uoY"
I tries something like following
def reverse_string(str)
arr = str.split(" ")
new_arr = arr.collect{|a| a.reverse}
new_arr.join(" ")
end
But it will not work for the strings which may have multiple blank spaces between the words.
Upvotes: 0
Views: 1692
Reputation: 42182
This one is the shortest possible and probably the fastest too. The string is regex'ed and all successive word characters are reversed in order
s = "How Are You"
s.gsub(/\w+/,&:reverse)
=>woH erA uoY
Upvotes: 3
Reputation: 16720
This works. Using a regex for spliting in Any word boundary character
def reverse_string str
arr = str.split /\b/
new_arr = arr.collect {|a| a.reverse}
new_arr.join
end
Upvotes: 0