Salil
Salil

Reputation: 47472

Reverse a words in string without change in order and also number of blank spaces in Ruby

I want to reverse all the words in a string such that

  1. Orders of the words should not be change
  2. Number of blank spaces in the words should be remain the same
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

Answers (3)

peter
peter

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

galymzhan
galymzhan

Reputation: 5523

s = "How     Are  You"
s.gsub(/\w+/) { |match| match.reverse }

Upvotes: 6

Ismael
Ismael

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

Related Questions