Donnerstag, 2. April 2009

format output in ruby

with #{ }

puts "Text is #{["Test 1", "Test 2"][1]}"
=>Text is Test 2

["Test 1", "Test 2"]
create array with "Test 1" and "Test 2"

["Test 1", "Test 2"][1]
choose second item [1]

print out as variable with #{}

simple outputs through strings objects


see info: ri String#%

format%argument => string

"%05d" % 123       fill with zero on numbers
=> "00123"

"%05s" % 123 do space
=> " 123"

"%-05s" % 123
=> "123 "

"%-5s: %08x" % [ "ID", self.object_id ]
=> "ID : fdbe224ac"
"%10.3f" % 123
=> " 123.000"

"%-10.3f" % 123
=> "123.000 "



output with sprintf analog to sprintf in c

see info: ri sprintf

format(format_string [, arguments...] ) => string
sprintf(format_string [, arguments...] ) => string

sprintf("%d %04x", 123, 123)
=> "123 007b"
sprintf("%08b '%4s'", 123, 123)
=> "01111011 ' 123'"
sprintf("%1$*2$s %2$d %1$s", "hello", 8)
=> " hello 8 hello"
sprintf("%1$*2$s %2$d", "hello", -8)
=> "hello -8"
sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23)
=> "+1.23: 1.23:1.23"
sprintf("%u", -123)
=> "..4294967173"

i,d integer
x hex
s string
b bit
e,f,g floating
%x$y x which argument, y what (i,d,s,..)
%1$*2$s argument 1 with length of argument 2 (string)