Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.chars.length vs string.length

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

like image 888
alassiter Avatar asked Apr 27 '11 16:04

alassiter


People also ask

What is the difference between string size and string length?

Using string::size: The method string::size returns the length of the string, in terms of bytes. Using string::length: The method string::length returns the length of the string, in terms of bytes. Both string::size and string::length are synonyms and return the exact same value.

What is the difference between chars and strings?

char is a primitive data type whereas String is a class in java. char represents a single character whereas String can have zero or more characters. So String is an array of chars. We define char in java program using single quote (') whereas we can define String in Java using double quotes (").

What do you mean by string length?

The length or size of a string means the total number of characters present in it. For Example: The string “Geeks For Geeks” has 15 characters (including spaces also).

What is the difference between string length () and array length?

Array Length field cannot be accessed as any normal field. String class objects are immutable and so we cannot use the final field with the String objects. In the case of String, class accessor methods have to be used by the class objects.


1 Answers

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.

like image 195
Dylan Markow Avatar answered Sep 23 '22 23:09

Dylan Markow