开发者

Using string[range]=new_val while respecting UTF8 in Ruby 1.8.7

开发者 https://www.devze.com 2023-03-15 11:31 出处:网络
I have code like text[from..to] = text_insertion The problem is that from and to a开发者_运维技巧re given counting UTF8 encoded characters as one char while the code above counts byte-wise in Ruby

I have code like

text[from..to] = text_insertion

The problem is that from and to a开发者_运维技巧re given counting UTF8 encoded characters as one char while the code above counts byte-wise in Ruby 1.8.7

I have to use Ruby 1.8.7

Which gem could I use to make my code work? I also can rewrite it to use String#substr or something similar, but I haven't found any lib that gives me methods that respect UTF8 encoding.


You can use ActiveSupport's String#mb_chars method. It let's you write something like this:

text.mb_chars[from..to] = text_insertion

It is available in all versions of ActiveSupport since 2.2.

0

精彩评论

暂无评论...
验证码 换一张
取 消