Ruby: Formatting String

,

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's the difference between {“puts”, “p”, “print”}?

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

blog comments powered by Disqus