rubyguides

String#length

str.length -> integer

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

The method takes no arguments and returns a plain integer — zero for an empty string, a positive number for anything else. Because the count is stored on the string object itself, the call finishes in constant time regardless of the text length, which makes it safe to use in hot loops and tight validation checks.

Parameters

This method takes no parameters.

Examples

Basic usage

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

"ruby".length
# => 4

"".length
# => 0

An empty string returns zero, which makes length a natural fit for guard clauses that check whether input was provided. The zero return is also useful as a base case in recursive string processing, where the empty string signals the end of the recursion without needing a separate sentinel value.

With Unicode characters

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

"🎉🎊🎈".length
# => 3

Each emoji is a single character to length, even though some emoji require multiple bytes and even multiple code points in UTF-8. Ruby hides that complexity by counting grapheme clusters as single characters, so the number you get from length matches what a person would count by looking at the text.

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

The validation pattern reads clearly: check the lower bound, then the upper bound. Both comparisons use length directly, which keeps the check self-contained and easy to adjust if the limits change. For more complex validation, you might extract the range into a constant and check (3..20).cover?(username.length), but the two-guard approach is clearer when each violation deserves its own error message.

Check if string is empty

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

empty?("")
# => true

empty?("hello")
# => false

Checking length.zero? is functionally identical to calling empty?, but the .zero? style reads naturally in guard clauses that compare against a numeric threshold. Both approaches are O(1) and equally fast, so the choice is a matter of readability: empty? says “is there anything here?”, while length.zero? fits better when the surrounding code already works with counts and limits.

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..."

Truncation with an ellipsis is a common UI pattern, and length makes the check straightforward: if the text fits, return it as-is; otherwise, take a prefix and append three dots. The character count from length keeps the truncation accurate even when the text includes multi-byte characters, because it measures what the user sees rather than the byte storage.

Pagination with slicing

text = "Ruby strings stay easy to count"
page_size = 10

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

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

Using length with [] for slicing is a concise way to paginate text. The first argument is the starting index, and the second is the number of characters to take. This works well with length because both operate at the character level, which keeps the pagination logic consistent regardless of whether the text contains ASCII or multi-byte characters.

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.

counting characters for simple checks

length is the simplest way to ask how many characters are in a piece of text, which makes it useful for validation, display limits, and a quick empty check. Because it returns a plain integer, the surrounding code can compare it directly against a limit without needing extra conversions or helper logic. That keeps the rule very easy to read in small scripts and everyday application code.

When the text may contain Unicode characters, the character count is still the right answer for most user-facing checks. It describes what the person sees, not how many bytes the text uses behind the scenes. If the code needs storage size instead, bytesize is the better tool, but for character counts, length stays the more natural choice.

That makes length a good default for most validation and display logic because it matches how people usually think about text limits. The code can ask for a count and compare it immediately, without any extra conversion or setup. In everyday Ruby, that small bit of directness is often exactly what the call site needs.

It is also a good companion to simple guard clauses because the code can reject too-short or too-long text without any extra ceremony. The method says what is being measured, and the comparison says what the limit is. That combination keeps the rule readable and the implementation easy to adjust later.

def valid_name?(name)
  name.length.between?(2, 50)
end

["Al", "Charlotte", ""].map { |n| valid_name?(n) }
# => [false, true, false]

It is a very common choice in examples because it keeps the focus on the condition, not on the mechanics of counting. A reader can see the limit, see the string, and understand the decision immediately. That is often the most practical shape for a length check in Ruby code.

That clarity is also why length shows up in so many small guard clauses. The method gives the code a plain number to compare, so the branch can stay short and readable. For everyday Ruby, that kind of direct comparison is often all the code needs.

See Also