Skip to content
Ruby

Strings

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

By EZ4Code Team
stringtext

Code

# 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

Explanation

Ruby strings are mutable sequences with rich interpolation and quoting options including heredocs and %q literals. Methods like sub, gsub, split, and join cover replacement and splitting, while =~ and scan work with regular expressions. The % operator mimics sprintf for formatted output.

More Ruby Snippets