Ruby: Formatting String

By Xah Lee. Date:

In Ruby, you can use any of {p, puts, print} to print.

You can embed variables or any Ruby code, like this:

# -*- coding: utf-8 -*-
# ruby

aa = 3

puts "#{aa} tigers" # 「3 tigers」

puts "#{3 + 4} tigers" # 「7 tigers」

Ruby also support the C style sprintf. Example:

#-*- coding: utf-8 -*-
# ruby

# integer
puts '%d' % 1234 # 「1234」

# padding by space
puts '%4d' % 12 # 「  12」

# float. 2 integer, 4 decimal
puts '%2.4f' % 3.123456789 # 「3.1235」

# string.
puts '%5s' % 'cats' # 「 cats」
puts '%2s' % 'cats' # 「cats」

puts '%2d◇%6d◇%2.4f◇%s' % [1234, 5678, 3.123456789, 'cats!'] # 「1234◇  5678◇3.1235◇cats!」

What is the difference between {puts, p, print}?

http://ruby-doc.org/core-1.9.3/Kernel.html#method-i-p

If you have a question, put $5 at patreon and message me.

  1. Ruby Basics
  2. Doc Lookup
  3. Print Version String
  4. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?

  1. Unicode 💎
  2. Quote String
  3. Quote Long String
  4. Format String
  5. String Operations
  6. True, False
  7. “if then else”
  8. for, while, Loop
  9. List
  10. Loop Thru List
  11. Hash Table
  12. Function Optional Parameter
  13. Map f to List
  14. Complex Numbers
  1. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  2. Predefined Global Variables