如何拆分字符串并跳过空格?

我有一个像" This is a test "的字符串。 我想用空格字符分割字符串。 我是这样做的:

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

结果是:

这个


一个
测试
这是一个测试

为什么最后一行"This is a test" ? 我需要的是,如果两个单词之间有两个或更多空格字符,那么这不应该返回“行”。

我只想得到在给定字符串中分割的单词。
有没有人有想法?

 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

如果省略pattern,则值为$; 用来。 如果$; 是nil(这是默认值),str在空格上分割,就像指定了`’一样。

你应该做

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

如果你不想要最后一个“这是一个测试”

因为

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

第一个命令“puts”将在每个块被激活之后放置。 省略第一个“放置”,你就完成了