Title here
Summary here
Ruby offers excellent support for string formatting. Here are some examples of common string formatting tasks.
# Define a Point class
Point = Struct.new(:x, :y)
# Main execution
p = Point.new(1, 2)
# Ruby offers several formatting methods for various data types
# For structs, use inspect or to_s
puts "struct1: #{p}"
puts "struct2: #{p.inspect}"
# To print the type of a value, use class
puts "type: #{p.class}"
# Formatting booleans
puts "bool: #{true}"
# There are many options for formatting integers
# Use to_s for standard base-10 formatting
puts "int: #{123}"
# This prints a binary representation
puts "bin: #{14.to_s(2)}"
# This prints the character corresponding to the given integer
puts "char: #{33.chr}"
# Use to_s(16) for hex encoding
puts "hex: #{456.to_s(16)}"
# For basic decimal formatting of floats, use sprintf or format
puts "float1: #{sprintf("%.6f", 78.9)}"
# Use sprintf with %e for scientific notation
puts "float2: #{sprintf("%e", 123400000.0)}"
puts "float3: #{sprintf("%E", 123400000.0)}"
# For basic string printing
puts "str1: #{'"string"'}"
# To include quotes, use %q
puts "str2: #{%q("string")}"
# Use unpack for hex representation of a string
puts "str3: #{"hex this".unpack('H*')[0]}"
# To print a representation of an object's id, use object_id
puts "pointer: #{p.object_id}"
# When formatting numbers you can control the width and precision
puts "width1: |#{sprintf("%6d%6d", 12, 345)}|"
# You can also specify the width of printed floats
puts "width2: |#{sprintf("%6.2f%6.2f", 1.2, 3.45)}|"
# To left-justify, use the - flag
puts "width3: |#{sprintf("%-6.2f%-6.2f", 1.2, 3.45)}|"
# For strings, use sprintf for width control
puts "width4: |#{sprintf("%6s%6s", "foo", "b")}|"
# To left-justify strings, use the - flag
puts "width5: |#{sprintf("%-6s%-6s", "foo", "b")}|"
# Ruby's equivalent of Sprintf is format
s = format("sprintf: a %s", "string")
puts s
# You can format and print to IO objects other than STDOUT
require 'stringio'
io = StringIO.new
io.puts format("io: an %s", "error")
puts io.string
Ruby’s string formatting capabilities are quite versatile. The sprintf
method (and its alias format
) provides printf-style formatting, while string interpolation offers a more Ruby-like approach. The %
operator can also be used for formatting, similar to sprintf
.
To run this program, save it as string_formatting.rb
and use:
$ ruby string_formatting.rb
This will output the formatted strings, demonstrating various formatting options available in Ruby.
Next, we’ll explore more advanced Ruby concepts and features.