String Methods
String methods are built-in tools for text that can change case, measure length, or trim spaces. It is like having a toolbox ready for every word.
In this page:
Syntax
string.length
string.upcase
string.downcase
string.include?("text")
string.reverse
String Methods
Ruby strings come with a large set of built-in methods for transformation and inspection, like .upcase, .downcase, .reverse, .length, and .strip.
Most string methods return a new string rather than modifying the original, following Ruby's general preference for non-mutating operations. Methods ending in ! (like .upcase!) mutate the string in place instead.
Note:
A method ending in ! (like upcase!) usually mutates the receiver in place -- the non-! version returns a new object instead.
Example: String Methods
text = " Hello, Ruby! "
puts text.strip
puts text.strip.upcase
puts text.strip.length
puts text.strip.reverse
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Expecting
text.stripto changetext, when it returns a new string unless you usestrip!. - Calling a bang method like
upcase!and using the result, when it returnsnilif nothing changed. - Confusing
lengthwith the number of bytes, when Ruby counts characters (usebytesizefor bytes).
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: