且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 Ruby 中的较大字符串中提取单个字符(作为字符串)?

更新时间:2023-02-26 09:11:24

在 Ruby 1.9 中,这很容易.在 Ruby 1.9 中,字符串是可识别编码的字符序列,因此您只需对其进行索引即可从中获得单字符字符串:

In Ruby 1.9, it's easy. In Ruby 1.9, Strings are encoding-aware sequences of characters, so you can just index into it and you will get a single-character string out of it:

'µsec'[0] => 'µ'

然而,在 Ruby 1.8 中,字符串是字节序列,因此完全不知道编码.如果您索引到一个字符串并且该字符串使用多字节编码,则您可能会直接索引到多字节字符的中间(在此示例中,'µ' 以 UTF-8 编码):

However, in Ruby 1.8, Strings are sequences of bytes and thus completely unaware of the encoding. If you index into a string and that string uses a multibyte encoding, you risk indexing right into the middle of a multibyte character (in this example, the 'µ' is encoded in UTF-8):

'µsec'[0] # => 194
'µsec'[0].chr # => Garbage
'µsec'[0,1] # => Garbage

但是,Regexps 和一些专门的字符串方法至少支持一小部分流行编码,其中包括一些日语编码(例如 Shift-JIS)和(在本例中)UTF-8:

However, Regexps and some specialized string methods support at least a small subset of popular encodings, among them some Japanese encodings (e.g. Shift-JIS) and (in this example) UTF-8:

'µsec'.split('')[0] # => 'µ'
'µsec'.split(//u)[0] # => 'µ'