Strings

Interpolation, common string methods, format, and regular expressions with scan, =~ and [].

Runs in Zerethon IDE · Ruby 4.0 Official Ruby documentation ↗
main.rb
name = "Ada Lovelace"
puts "#{name} has #{name.length} characters"
puts "#{name.upcase} #{name.downcase} #{name[0, 3]}"
puts "  padded  ".strip + "|"
puts "a,b,c".split(",").inspect, %w[x y z].join("-")
puts "#{name.sub("Ada", "Augusta")} #{name.start_with?("Ada")} #{name.downcase.include?("love")}"
puts format("%.2f %5d %03d", 3.14159, 42, 7)

text = "Order 12 shipped, order 7 pending"
puts text.scan(/\d+/).inspect
puts text[/order (\d+) pending/, 1]
puts text =~ /shipped/ ? "has shipped" : "nothing shipped"
puts text.gsub(/\d+/) { |n| (n.to_i * 2).to_s }

Output

Ada Lovelace has 12 characters
ADA LOVELACE ada lovelace Ada
padded|
["a", "b", "c"]
x-y-z
Augusta Lovelace true true
3.14    42 007
["12", "7"]
7
has shipped
Order 24 shipped, order 14 pending
  • sub replaces the first match, gsub every match; both take a string or a regular expression.
  • length counts characters, so "héllo".length is 5; bytesize counts bytes.
  • str[/regex/, 1] returns the first capture group, or nil when there is no match.
  • Strings can change: << appends in place. Add # frozen_string_literal: true at the top of a file to make literals read-only.

Related topics

Official references