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:
# ruby aa = 3 puts "#{aa} tigers" # 「3 tigers」 puts "#{3 + 4} tigers" # 「7 tigers」
Ruby also support the C style sprintf. Example:
# 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}?
puts
prints in a human readable form, and adds newline after each argument. For example, string is printed without quotes, array are printed without the brackets or separators.p
prints in a technical form. For example, string will include the quotes. This is good for debugging.print
is similar to “puts” but does not add newline.