如何在 Ruby 中解析制表符分隔的文本行?

发布于 2024-07-14 06:26:59 字数 225 浏览 5 评论 0原文

我发现 Ruby 的 each 函数有点令人困惑。 如果我有一行文本,each 循环将为我提供每个空格分隔的单词,而不是每个单独的字符。

那么检索由制表符分隔的字符串部分的最佳方法是什么。 目前我有:

line.split.each do |word|
...
end

但这并不完全正确。

I find Ruby's each function a bit confusing. If I have a line of text, an each loop will give me every space-delimited word rather than each individual character.

So what's the best way of retrieving sections of the string which are delimited by a tab character. At the moment I have:

line.split.each do |word|
...
end

but that is not quite correct.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

能否归途做我良人 2024-07-21 06:26:59

我不确定我完全理解你的问题,但是如果你想在制表符上分割行,你可以将其指定为 split: 的参数,

line.split("\t").each ...

或者你可以将其指定为正则表达式:

line.split(/\t/).each ...

每个基本上只是迭代所有数组中的项目, split 从字符串生成数组。

I'm not sure I quite understand your question, but if you want to split the lines on tab characters, you can specify that as an argument to split:

line.split("\t").each ...

or you can specify it as a regular expression:

line.split(/\t/).each ...

Each basically just iterates through all the items in an array, and split produces an array from a string.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文