arled
arled

Reputation: 2690

Reduce long white spaces to a single character

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?

Upvotes: 1

Views: 74

Answers (5)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34318

[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!

Upvotes: 0

sawa
sawa

Reputation: 168091

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

Upvotes: 2

nronas
nronas

Reputation: 181

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

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

Hope that helps.

Upvotes: 3

bjhaid
bjhaid

Reputation: 9752

str = hello world    how     are  you

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

# => hello#world#how#are#you

Upvotes: 2

Yedhu Krishnan
Yedhu Krishnan

Reputation: 1245

Try:

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

Upvotes: 6

Related Questions