1

I'm using ruby and I'm trying to reduce a long white spaces to a single character. This is the code I'm trying:

str = hello world    how     are  you 
puts str.gsub(/\s/, '#')

Output of my current code:

hello#world####how#####are##you

Desired output:

hello#world#how#are#you

Any idea how to reach my desired output?

5 Answers 5

6

Try:

puts str.gsub(/\s+/, '#')
3

You are close, you missing the matching of the regex for more than one spaces. Try this:

str.gsub(/\s+/, '#')

Hope that helps.

2
str = hello world    how     are  you

puts str.gsub(/\s+/, '#')

# => hello#world#how#are#you
2
"hello world    how     are  you"
.squeeze(" ").tr(" ", "#")
# => "hello#world#how#are#you"
0

[As the user Iain asked for explanation of what I did]

In Regex, \s+ means 1 or more whitespace character. Using, ruby's gsub method, I am replacing the matching pattern ( in this case, 1 or more whitespace characters) with the '#' character. And, I am testing this example code in irb.

    1.9.3-p327 :013 > str = "hello world    how     are  you" 
     => "hello world    how     are  you"  
    1.9.3-p327 :016 > str.gsub(/\s+/, '#')
     => "hello#world#how#are#you" 

extra tip: rubular is a great online tool to test and play with Regexp!

1
  • Please can you leave an explanation of what you doing?
    – Iain
    Jul 10, 2014 at 21:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.