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/).lengthExplanation
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
Blocks, Procs, Lambdas
Use blocks with yield, Procs, lambdas, and the & operator.
Classes and Modules
Define classes with inheritance, mix in modules, and add class methods.
Iterators
Use each, map, select, reduce, group_by, and lazy enumerators.
Hashes
Build, default, transform, merge, and group with Hash.
Metaprogramming
Define methods dynamically, intercept with method_missing, and build DSLs.
Error Handling
Raise and rescue typed exceptions with ensure and retry.