迭代相同大小的子串
我想将我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Ruby 1.9(和 1.8.7)中,您可以使用each_char 可靠地迭代字符串的字符,包括正确处理多字节字符等。 在早期版本中,each_char 不存在,索引将返回字节代码而不是单个字符字符串。 在这种情况下,您可以使用
它将以 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
which will split the string in a UTF-8 aware way.
There's some nice discussion here.
也许我不明白你的问题,但是在 Ruby 中,一个字符和一个包含 1 个字符的字符串没有区别。
Maybe I don't understand your question, but there's no difference between a character and a string of 1 character in Ruby.