typestar

String methods in Ruby

The everyday string toolkit: strip, split, sub and friends.

line = "  the well-grounded rubyist  "
puts line.strip
puts line.strip.split.first

title = "ruby under a microscope"
puts title.capitalize
puts title.split.map(&:capitalize).join(" ")
puts title.sub("microscope", "lens")

puts title.start_with?("ruby")
puts title.tr("aeiou", "*")
puts title.center(30, "-")

How it works

  1. strip trims whitespace; split breaks a line into words.
  2. map(&:capitalize).join title-cases a phrase word by word.
  3. sub replaces the first match; tr swaps characters wholesale.
  4. center pads both sides — handy for quick console banners.

Keywords and builtins used here

The run, in numbers

Lines
12
Characters to type
308
Tokens
88
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 59 seconds.

Type this snippet

Step 2 of 3 in Variables & strings, step 2 of 29 in Language basics.

← Previous Next →

String methods in other languages