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

前端之家收集整理的这篇文章主要介绍了ruby – 如何拆分字符串并跳过空格?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个字符串,如“这是一个测试”.我想用空格字符分割字符串.我这样做:
puts " This   is a test ".strip.each(' ') {|s| puts s.strip}

结果是:

This

is
a
test
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

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.

猜你在找的Ruby相关文章