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?
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.
The . strip method removes the leading and trailing whitespace on strings, including tabs, newlines, and carriage returns ( \t , \n , \r ).
gsub() function is used to remove the space by removing the space in the given string.
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.
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+/, ' ')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With