Tim
Tim

Reputation: 13258

How to split a string and skip whitespace?

I have a string like " This is a test ". I want to split the string by the space character. I do it like this:

puts " This   is a test ".strip.each(' ') {|s| puts s.strip}

The result is:

This

is
a
test
This is a test

Why is there the last line "This is a test"? And I need, that if there are two or more space characters between two words, that this should not return a "row".

I only want to get the words splitted in a given string.
Does anyone have an idea?

Upvotes: 12

Views: 60094

Answers (3)

Martin Labuschin
Martin Labuschin

Reputation: 516

The first command "puts" will be put after the each-block is excecuted. omit the first "puts" and you are done

Upvotes: 1

YOU
YOU

Reputation: 123831

irb(main):002:0> " This   is a test ".split
=> ["This", "is", "a", "test"]

irb(main):016:0* puts " This   is a test ".split
This
is
a
test

str.split(pattern=$;, [limit]) => anArray

If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ’ were specified.

Upvotes: 41

marcgg
marcgg

Reputation: 66436

You should do

" This   is a test ".strip.each(' ') {|s| puts s.strip}

If you don't want the last "this is a test"

Because

irb>>> puts " This   is a test ".strip.each(' ') {}
This   is a test

Upvotes: 2

Related Questions