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

标签 ruby string split

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

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

结果是:

This

is
a
test
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 - 如何拆分字符串并跳过空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2005148/

相关文章:

ruby - 理解 Ruby 中 Proc.curry 方法的 arity 参数

ruby - 使用 Rails 和 Redis 创建多个作业

ruby-on-rails - SessionsController 中的 NoMethodError#destroy 未定义方法 `forget' for nil :NilClass

python - 解析python中的数学表达式并求解以找到答案

JavaScript - 将字符串拆分为单词、识别元音最多的单词的函数 - 使用 For 循环

javascript - 使用 split() 方法分割字符串

Ruby:1.9 中的 parsedate 去哪儿了?

Java 在字符串之前添加填充 BJP4 练习 3.17 : padString

javascript - 在对象数组中搜索字符串

c# - 没有小数点的 double 格式