String Methods Overview
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 1 of 56.
Ruby gives strings a deep collection of built-in methods for common transformations. You don't need extra libraries, they're part of every string you create.
Some of the most useful ones change case or remove whitespace:
name = " Alice "
puts name.strip # "Alice"
puts name.upcase # " ALICE "
puts name.downcase # " alice "
puts name.reverse # " ecilA "Others tell you something about the string:
word = "hello"
puts word.length # 5
puts word.include?("ell") # true
puts word.start_with?("he") # trueMost of these return a new string. The original stays untouched unless you use the bang version (e.g. upcase!).
Challenge
BeginnerRead a single line of input. Print, on separate lines:
- The input with leading and trailing whitespace removed
- That trimmed value in uppercase
- The length of the trimmed value
trueorfalse: does the trimmed value contain"ruby"(case-insensitive)?
For input Hello Ruby world , the output is:
Hello Ruby world
HELLO RUBY WORLD
16
trueCheat sheet
Common Ruby string methods:
name = " Alice "
name.strip # "Alice" - removes leading/trailing whitespace
name.upcase # " ALICE "
name.downcase # " alice "
name.reverse # " ecilA "
word = "hello"
word.length # 5
word.include?("ell") # true
word.start_with?("he") # trueMost methods return a new string; use the bang version (e.g. upcase!) to modify in place.
Try it yourself
input = gets.chomp
# TODO: print the four required lines
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier