Finding the length of a string

Ruby:
Finding the length of a string

How to:

Ruby keeps it simple with the .length method:

greeting = "Hello, world!"
puts greeting.length

Output:

13

Or, use .size which does the same thing:

greeting = "Hello, world!"
puts greeting.size

Output:

13

Deep Dive

In Ruby, .length and .size are interchangeable when it comes to strings; they give you the character count. Historically, Ruby has focused on making the code more natural to read, which is why you often find more than one way to do the same thing.

Internally, each character in a string affects the storage size. So, knowing the number can be essential for optimization, especially with massive amounts of text.

While .length and .size give you the character count, in some languages and earlier times, a string’s length might refer to its byte size. Ruby with its multibyte character support via Unicode, however, does not equate byte size directly to string length due to characters possibly taking more than one byte.

Alternatives like .bytesize tell you how many bytes a string takes up, and .chars.count gives you the number of characters by first converting the string into an array of characters.

Here’s how you would use .bytesize and .chars.count:

greeting = "Hello, world!"
puts greeting.bytesize
puts greeting.chars.count

Output:

13
13

See Also