How to Find Length of String in Ruby: Simple Guide
In Ruby, you can find the length of a string using the
.length method. This method returns the number of characters in the string as an integer.Syntax
The syntax to find the length of a string in Ruby is simple. You call the .length method on any string object.
string.length: Returns the number of characters instring.
ruby
string = "hello"
length = string.lengthExample
This example shows how to use the .length method to get the number of characters in a string and print it.
ruby
name = "Ruby" puts "The length of '#{name}' is #{name.length}."
Output
The length of 'Ruby' is 4.
Common Pitfalls
One common mistake is confusing .length with .size. In Ruby, both work the same for strings, but .length is clearer for beginners.
Another pitfall is forgetting that .length counts all characters including spaces and special characters.
ruby
text = "hello world" puts text.length # Correct: counts all characters including space # To get length without spaces puts text.length - text.count(' ')
Output
11
10
Quick Reference
Use .length to get the number of characters in a string. It returns an integer. Spaces and special characters are included in the count.
| Method | Description | Example | Output |
|---|---|---|---|
| .length | Returns number of characters in string | "hello".length | 5 |
| .size | Alias for .length, same result | "hello".size | 5 |
Key Takeaways
Use the .length method to find the number of characters in a Ruby string.
.length counts all characters including spaces and special symbols.
.size is an alias of .length and works the same way.
Remember to call .length on a string object, not on nil or other types.