Reputation: 505
I'm migrating from Rails 2.1.2 to 2.3.5 and one of the items that doesn't work anymore is
"string".chars.length
I used the console to discover that "string".chars is a ActiveSupport method in 2.1.2 and an Enumerable in 2.3.5
So, in completing this migration, I was wondering what the difference is in using
"string".chars.length
vs
"string".length
Will they return the same thing? They appear to, I just wanted to know if you know the difference so I can learn?
Thanks
Upvotes: 8
Views: 19436
Reputation: 124429
If you were using the #chars
method because you were dealing with unicode strings, then you can use #mb_chars
instead, and this is probably your best bet to guarantee your code acts the exact same as it did in 2.1.2:
"string".mb_chars.length
=> 6
However, if you're using Ruby 1.9, or if you're on Ruby 1.8 but don't need to deal with any unicode strings, you can just use "string".length
. (In Ruby 1.9, #mbchars
just returns self
anyway since 1.9 has much better support for unicode strings.)
See the API documentation for more info.
Upvotes: 13