开发者

Changing the order of arguments in ruby 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开发者_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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜