Skip to content
Ruby

Strings

Interpolate, trim, split, replace, and pattern-match strings.

#string#text

Code

ruby
# Interpolation and quoting
name = "Ruby"
puts "Hello, #{name}!"
puts 'No interpolation: #{name}'
puts %q(single quoted)
puts %Q(double #{name})

# Multiline heredoc
text = <<~TEXT
  Indented
  heredoc
TEXT
puts text

# Concatenation and repetition
puts "ab" + "cd"
puts "x" * 5

# Length and case
s = "Hello World"
puts s.length
puts s.upcase
puts s.downcase
puts s.swapcase

# Substring
puts s[0, 5]               # "Hello"
puts s[-5..]               # "World"

# Replace
puts s.sub("o", "0")       # first
puts s.gsub("o", "0")      # all

# Split and join
puts "a,b,c".split(",").inspect
puts %w[a b c].join("-")

# Format
puts "%s has %d chars" % [name, name.length]

# Regex
if s =~ /World/
  puts "matches"
end
puts s.scan(/l/).length