# How to Remove Whitespace from a String in Ruby

*Published on January 01, 2024*

---


The simplest way to remove leading and trailing whitespaces around a string is to use the&nbsp;[`String#strip`](https://docs.ruby-lang.org/en/3.2/String.html#method-i-strip)&nbsp;function. It returns a copy of the string (without modifying the original) with whitespace removed from both ends.

```ruby
puts "  hello ".strip

# "hello"
```

If you want to modify the original string, use the bang (!) version of the strip method as follows:

```ruby
name = " Ruby "
puts name  # " Ruby "

name.strip!
puts name  # "Ruby"
```

In addition, Ruby also provides&nbsp;`lstrip`,&nbsp;`lstrip!`,&nbsp;`rstrip`, and&nbsp;`rstrip!`&nbsp;methods to remove whitespaces from only one end of the string.

```ruby
input = "  Ruby on Rails     "

puts input.strip    # "Ruby on Rails"
puts input.lstrip   # "Ruby on Rails     "
puts input.rstrip   # "  Ruby on Rails"
```

### Remove All Whitespace in a String

If the string contains extra whitespace inside, you can use the&nbsp;[`String#gsub`](https://docs.ruby-lang.org/en/3.2/String.html#method-i-gsub)&nbsp;method to replace it using a regex.

```ruby
input = "  Ruby   on   Rails   "

puts input.gsub(/\s+/, "")    # RubyonRails
```

In the above code, the&nbsp;`/\s+/`&nbsp;regular expression means one or more whitespace (spaces, newlines, or tabs).

Note how it removed all whitespace both around and inside the string, resulting in&nbsp;`RubyonRails`, which you may or may not want.

The&nbsp;[`squish`](https://api.rubyonrails.org/classes/String.html#method-i-squish)&nbsp;method in Rails provides a nice alternative by removing&nbsp;**only the extra space**&nbsp;inside the string. That is, it first removes all whitespace on both ends of the string, and then changes remaining consecutive whitespace groups into one space each.

```ruby
input = "  Ruby   on   Rails   "

input.squish    # "Ruby on Rails"
```

Pretty handy.

**Bonus:**&nbsp;If you want to remove just the last character in a string (doesn't matter if it's a whitespace or not), use the&nbsp;`String#chop`&nbsp;method.

```ruby
puts "whoops".chop

# "whoop"
```

### **What is Considered a Whitespace in Strings?**

In Ruby's&nbsp;`String`&nbsp;class,&nbsp;_whitespace_&nbsp;is defined as a contiguous sequence of characters consisting of any mixture of the following:

- NL (null):&nbsp;`"\x00"`,&nbsp;`"\u0000"`.
- HT (horizontal tab):&nbsp;`"\x09"`,&nbsp;`"\t"`.
- LF (line feed):&nbsp;`"\x0a"`,&nbsp;`"\n"`.
- VT (vertical tab):&nbsp;`"\x0b"`,&nbsp;`"\v"`.
- FF (form feed):&nbsp;`"\x0c"`,&nbsp;`"\f"`.
- CR (carriage return):&nbsp;`"\x0d"`,&nbsp;`"\r"`.
- SP (space):&nbsp;`"\x20"`,&nbsp;`" "`.

