开发者

Changing the order of arguments in ruby sprintf

开发者 https://www.devze.com 2022-12-26 09:41 出处:网络
Is it possible to change the order of parameters to sprintf? like sprintf(\" this is %arg[2] test %arg[1]\" , arg1, arg2)

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开发者_StackOverflow中文版 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消