Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby reduce all whitespace to single spaces

Tags:

ruby

I'm not sure how do this, as I'm pretty new to regular expressions, and can't seem to find the proper method to accomplish this but say I have the following as a string (all tabs, and newlines included)

1/2 cup                   onion                         (chopped) 

How can I remove all the whitespace and replace each instance with just a single space?

like image 835
JP Silvashy Avatar asked Jan 11 '11 20:01

JP Silvashy


People also ask

How do you remove white spaces in Ruby?

Ruby has lstrip and rstrip methods which can be used to remove leading and trailing whitespaces respectively from a string. Ruby also has strip method which is a combination of lstrip and rstrip and can be used to remove both, leading and trailing whitespaces, from a string.

How do you strip in Ruby?

The . strip method removes the leading and trailing whitespace on strings, including tabs, newlines, and carriage returns ( \t , \n , \r ).

How do I get rid of extra spaces in R?

gsub() function is used to remove the space by removing the space in the given string.

What is whitespace in Ruby?

Whitespace in Ruby ProgramWhitespace characters such as spaces and tabs are generally ignored in Ruby code, except when they appear in strings. Sometimes, however, they are used to interpret ambiguous statements.


2 Answers

This is a case where regular expressions work well, because you want to treat the whole class of whitespace characters the same and replace runs of any combination of whitespace with a single space character. So if that string is stored in s, then you would do:

fixed_string = s.gsub(/\s+/, ' ') 
like image 168
Chuck Avatar answered Sep 28 '22 16:09

Chuck


Within Rails you can use String#squish, which is an active_support extensions.

require 'active_support'  s = <<-EOS 1/2 cup                onion EOS  s.squish # => 1/2 cup onion 
like image 39
sschmeck Avatar answered Sep 28 '22 16:09

sschmeck