things = "one thing, two things, three things, four things"

有了这个输入,我如何用逗号分割一个字符串,然后将其周围的空格修剪到位?导致:

things = ["one thing", "two things", "three things", "four things"]

目前我有:

things = things.to_s.tr("\n\t", "").strip.split(/,/)

这完成了我希望它完成的大部分工作,除了在逗号上拆分时删除前导/尾随空格.实现这一目标的最佳方式是什么?我想把它作为这个表达式的一部分,而不是把上面的结果赋给一个单独的数组,然后对它进行迭代.

推荐答案

s = "one thing, two things, three things, four things"
s.split(",").map(&:strip)
# => ["one thing", "two things", "three things", "four things"]

在我的Ubuntu 13.04操作系统中,使用Ruby 2.0.0p0

require 'benchmark'

s = "one thing, two things, three things, four things"
result = ""

Benchmark.bmbm do |b|
  b.report("strip/split: ") { 1_000_000.times {result = s.split(",").map(&:strip)} }
  b.report("regex: ") { 1_000_000.times {result = s.split(/\s*,\s*/)} }
end

Rehearsal -------------------------------------------------
strip/split:    6.260000   0.000000   6.260000 (  6.276583)
regex:          7.310000   0.000000   7.310000 (  7.320001)
--------------------------------------- total: 13.570000sec

                    user     system      total        real
strip/split:    6.350000   0.000000   6.350000 (  6.363127)
regex:          7.290000   0.000000   7.290000 (  7.302163)

Ruby相关问答推荐

这是按引用传递/值传递的误解,导致此方法无法按预期输出吗?

Ruby:如何在 vanilla ruby​​ 中使用有效支持日期?

Ruby:如何将两个返回值连接到一行中的两个字符串

Ruby注入daisy链?

Rack并发 - rack.multithread、async.callback 或两者兼而有之?

Rails 3 - 限制资源路径中的操作格式

在 Ruby 中,获取第一个块返回 true 的可枚举元素的最快方法是什么?

确定字符串数组是否包含ruby中的某个子字符串

来自 Linux 上的命令队列的并行处理(bash、python、ruby ......随便)

Ruby 中的 main是什么?

将 Ruby 哈希转换为 YAML

动态设置 Ruby 对象的属性

相当于 Ruby 中的通过

如何在 Ruby 脚本中运行 Rake 任务?

带有添加和删除参考的 Rails 迁移

如何在 gemspec 中指定最低 Ruby 版本?

在 Ruby 中解析制表符分隔文件的最佳方法是什么?

从 'mm/dd/yyyy' 格式解析 ruby​​ DateTime

将浮点数舍入到Ruby中最接近的整数

什么是 Ruby 1.9 标准 CSV 库?