Ruby split by whitespace

JJ Beck picture JJ Beck · Nov 24, 2012 · Viewed 44.8k times · Source

How can I write a Ruby function that splits the input by any kind of whitespace, and remove all the whitespace from the result? For example, if the input is

 aa bbb
cc    dd ee

Then return an array ["aa", "bbb", "cc", "dd", "ee"].

Answer

Ajedi32 picture Ajedi32 · Aug 1, 2014

This is the default behavior of String#split:

input = <<-TEXT
 aa bbb
cc    dd ee
TEXT

input.split

Result:

["aa", "bbb", "cc", "dd", "ee"]

This works in all versions of Ruby that I tested, including 1.8.7, 1.9.3, 2.0.0, and 2.1.2.