Is it possible to change the order of parameters to sprintf
?
like sprintf(" this is %arg[2] test %arg[1]" , arg1, arg2)
I need to dynamically change the order of the arguments so is that possible with sprintf
?
Is it possible to change the order of parameters to sprintf
?
like sprintf(" this is %arg[2] test %arg[1]" , arg1, arg2)
I need to dynamically change the order of the arguments so is that possible with sprintf
?
Yes.
irb(main):007:0> arg1 = 'foo'
=> "foo"
irb(main):008:0> arg2 = 'bar'
=> "bar"
irb(main):009:0> sprintf("%3$0.3f this is %2$s test %1$s" , arg1, arg2, Math::PI)
=> "3.142 this is bar test foo"
The format is %N$fmt
where N indicates the ordinal position of the argument, and fmt
is what you would put after the %
sign when using sprintf
normally.