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
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.
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 (").
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With