String.length / size
Methods for getting the length (number of characters) of a string. Both length and size behave identically.
Syntax
# Returns the length (number of characters) of the string. str.length str.size # Returns the byte size of the string. str.bytesize # Returns true if the string is empty. str.empty?
Method List
| Method | Description |
|---|---|
| length | Returns the number of characters in the string as an integer. Multibyte characters are each counted as one character. |
| size | An alias for length. Behaves identically. |
| bytesize | Returns the byte size of the string. Japanese characters in UTF-8 are counted as 3 bytes per character. |
| empty? | Returns true if the string is empty (length 0), or false otherwise. |
Sample Code
# Get the character count of an ASCII string.
greeting = "Hello"
puts greeting.length # 5
puts greeting.size # 5 (same as length)
# Get the character count of a Japanese string.
name = "山田太郎"
puts name.length # 4
puts name.bytesize # 12 (3 bytes per character in UTF-8)
# Check whether a string is empty.
input = ""
if input.empty?
puts "Input is empty." # This line is output.
else
puts "Input: #{input}"
end
# Use character count for input validation.
username = "田中一郎"
if username.length > 20
puts "Username must be 20 characters or fewer."
else
puts "Username accepted." # This line is output.
end
Overview
Ruby's length and size are methods that return the number of characters in a string. Since both behave identically, you can use either one. Multibyte characters such as Japanese are correctly counted as a single character each, so you won't encounter the mismatch between byte count and character count that occurs with PHP's strlen().
If you need the byte size, use bytesize. To check whether a string is empty, empty? is the clearest option — it expresses the intent more explicitly than writing length == 0.
To search for a specific character or substring within a string, use include? or index.
If you find any errors or copyright issues, please contact us.