.length
Try it yourself →Returns the number of characters.
Syntax
text.length
Description
Returns the length of the string (same as .size).
Example
puts "merhaba".length
Expected output
7
When to use?
Length check.
String methods: length, transformation, replacement, splitting.
| Command | Description |
|---|---|
| .length | Returns the number of characters. |
| upcase / downcase / capitalize | Changes the letter case. |
| strip / chomp | Cleans up whitespace. |
| gsub / sub | Replaces a part of the string. |
| split / join | Splits text into an array / joins an array into text. |
| include? / index | Is a substring present / where is it? |
Returns the number of characters.
Syntax
text.length
Description
Returns the length of the string (same as .size).
Example
puts "merhaba".length
Expected output
7
When to use?
Length check.
Changes the letter case.
Syntax
text.upcase
Description
upcase makes uppercase, downcase lowercase, capitalize capitalizes the first letter. Returns a new text.
Example
puts "ada".upcase puts "ADA".downcase puts "ada lovelace".capitalize
Expected output
ADA ada Ada lovelace
When to use?
Comparison, representation.
Cleans up whitespace.
Syntax
text.strip
Description
strip removes leading/trailing spaces, chomp removes the trailing newline.
Example
puts " space ".strip
Expected output
space
When to use?
Input sanitization.
Replaces a part of the string.
Syntax
text.gsub(old, new)
Description
gsub replaces all matches, sub replaces only the first one.
Example
puts "leo leo".gsub("leo", "emma")Expected output
emma emma
When to use?
Text cleaning, templating.
Splits text into an array / joins an array into text.
Syntax
text.split(separator) · arr.join(separator)
Description
split breaks into parts (arr); join does the reverse.
Example
p "a,b,c".split(",")
puts ["x", "y", "z"].join("-")Expected output
["a", "b", "c"] x-y-z
When to use?
CSV parsing, arr↔text.
Is a substring present / where is it?
Syntax
text.include?(part)
Description
include? returns true/false, index returns the position (or nil if missing). Methods ending with ? return true/false.
Example
puts "education".include?("cat")
puts "merhaba".index("hab")Expected output
true 3
When to use?
Search, content check.