tags:

views:

929

answers:

3

Hello!

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?

Thanks a lot in advance & Best Regards

+7  A: 
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.

S.Mark
" This is a test ".split
khelll
Thanks, I admit that I am not good at ruby.
S.Mark
+2  A: 

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
marcgg
A: 

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

Labuschin