Menu

Toshimaru's Blog

Remove line breaks from String in Ruby

How do you remove line break from string in Ruby?

> puts "a\nb\nc"
a
b
c

In Ruby

delete

Just delete line breaks.

> "a\nb\nc".delete("\n")
=> "abc"

ref. (Japanese) Array#delete

tr

Replace line breaks with tabs.

> "a\nb\nc".tr("\n", "\t")
=> "abc"

ref. (Japanese) String#tr

In Rails

squish

In Rails, squish can be used. line breaks are replaced with white spaces.

> "a\nb\nc".squish
=> "a b c"

All whitespace characters are replaced with one white spaces.

> "   a\nb\tc   ".squish
=> "a b c"

ref. String squish()

Load more