String.length / size
| Since: | Ruby 1.8(2003) |
|---|
Methods for getting the length (number of characters) of a string. Both length and size behave identically.
Syntax
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
sample_string_length_size.rb
greeting = "Hello"
puts greeting.length # 5
puts greeting.size # 5 (same as length)
# Get the character count of a Japanese string.
name = "綾波レイ" # Ayanami Rei (Evangelion)
puts name.length # 4 (4 characters)
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 = "Ikari Shinji"
if username.length > 20
puts "Username must be 20 characters or fewer."
else
puts "Username accepted." # This line is output.
end
Running the above produces the following output:
ruby string_length_size.rb 5 5 4 12 Input is empty. Username accepted.
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.