I started learning Ruby 2 days ago and so far it has been a refreshing language. The basic data types are much the same, excepting symbol (see Ruby docs) which is new to me, but that is a story for another day. This short article is about removing whitespaces from strings in Ruby.
What are strings?
In Ruby, strings are a sequence of one or more characters; like letters, numbers or symbols, wrapped in either single or double quotes. Strings can also be stored in variables.
#Str using double quotes
puts "I am a string."
#Str of numbers using single quotes
puts '54321'
#Storing strings as variables
str1 = "Yep, the numbers above are also strings."
#displaying output
puts str1
Output:
I am a string.
54321
Yep, the numbers above are also strings.
What are whitespaces?
Whitespace is defined as any of the following characters: null, horizontal tab, line feed, vertical tab, form feed, carriage return, space (
\t
,\n
,\v
,\r
,\f
,\s
).
—source: Ruby-doc.org
String Methods for trimming whitespaces:
-
#strip—
The
.strip
method removes leading and trailing whitespaces from a string and returns a copy of the string.
puts " I am a string ".strip #=> I am a string
puts "\t\tHello strings\n".strip #=> Hello strings
.strip
removes only whitespaces that occur in front of (leading) or at the end of (trailing) a string. It will not remove spaces in between characters.
-
#gsub—
The
.gsub
method replaces a given pattern from a string with the second argument and returns a copy of the string.
puts "white space".gsub(/[[:space:]]/, "") #=> whitespace
puts "many white spaces".gsub(/\s+/, "") #=> manywhitespaces
The patterns used in this example are both the Regexp for space. The second argument passed to .gsub
is an empty string. So .gsub
looks for all the spaces in the string as the pattern requires and removes them, as required by the empty string in the second argument.
Top comments (0)