迭代相同大小的子串

发布于 2024-07-13 16:32:02 字数 74 浏览 3 评论 0原文

我想将我的 String 对象转换为其 1 大小的子字符串(不是字符)的 Enumerable,如何在 Ruby 中有效地完成此操作?

I want to convert my String object to Enumerable of its 1-sized substrings (not chars), how can I do this efficiently in Ruby?

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

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

发布评论

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

评论(3

一场春暖 2024-07-20 16:32:02
"xyzzy".split(//) => ["x", "y", "z", "z", "y"]
"xyzzy".split(//) => ["x", "y", "z", "z", "y"]
°如果伤别离去 2024-07-20 16:32:02

在 Ruby 1.9(和 1.8.7)中,您可以使用each_char 可靠地迭代字符串的字符,包括正确处理多字节字符等。 在早期版本中,each_char 不存在,索引将返回字节代码而不是单个字符字符串。 在这种情况下,您可以使用

"abcdefg".split(//u)

它将以 UTF-8 感知方式分割字符串。

这里有一些很好的讨论。

In Ruby 1.9 (and 1.8.7) you can use each_char to reliably iterate over the characters of a string, including proper handling of multi-byte chars and stuff. In earlier releases, each_char does not exist and indexing will return byte codes rather than single char strings. In this case, you can use

"abcdefg".split(//u)

which will split the string in a UTF-8 aware way.

There's some nice discussion here.

却一份温柔 2024-07-20 16:32:02

也许我不明白你的问题,但是在 Ruby 中,一个字符和一个包含 1 个字符的字符串没有区别。

'hello world'.each_char {|c| puts "substring is #{c}"}

Maybe I don't understand your question, but there's no difference between a character and a string of 1 character in Ruby.

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