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. Unicode 💎
  5. Quote String
  6. Quote Long String
  7. Format String
  8. String Operations
  9. True, False
  10. “if then else”
  11. for, while, Loop
  12. List
  13. Loop Thru List
  14. Hash Table
  15. Function Optional Parameter
  16. Map f to List
  17. Complex Numbers
  18. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  19. Predefined Global Variables
  20. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?