String#length

str.length -> integer
Returns: Integer · Updated March 13, 2026 · String Methods
string length size characters

String#length returns the number of characters in a string. It is useful for validating input length, checking if a string is empty, and various other string manipulations.

Syntax

string.length

Parameters

This method takes no parameters.

Examples

Basic usage

hello = "Hello, World!"
hello.length
# => 13

"ruby".length
# => 4

"".length
# => 0

With Unicode characters

"こんにちは".length
# => 5

"🎉🎊🎈".length
# => 3

Common Patterns

Validate string input length

def validate_username(username)
  if username.length < 3
    raise ArgumentError, "Username must be at least 3 characters"
  end
  if username.length > 20
    raise ArgumentError, "Username must be at most 20 characters"
  end
  true
end

Check if string is empty

def empty?(string)
  string.length.zero?
end

empty?("")
# => true

empty?("hello")
# => false

Truncate long text

def truncate(text, max_length)
  return text if text.length <= max_length
  text[0, max_length - 3] + "..."
end

truncate("Hello, World!", 8)
# => "Hello..."

Pagination with slicing

text = "Lorem ipsum dolor sit amet"
page_size = 10

text[0, page_size]
# => "Lorem ipsu"

text[page_size, page_size]
# => "m dolor si"

Performance Notes

length runs in O(1) constant time for most Ruby implementations because the string object stores the character count as an instance variable. It does not require traversing the entire string.

Errors

This method never raises an error. It works on any string object and returns an integer, even for empty strings.

See Also