Hi,
This is a pretty simple question. I need to do a “printf” of some
numbers inside a string. I just can’t figure out how to express a long
string that has that “printf” inside it, because the printf statement
itself has quotes, too. I just need the number to end up being
zero-padded to 3 characters. So, for “3,” I want “003.”
Hi,
This is a pretty simple question. I need to do a “printf” of some
numbers inside a string. I just can’t figure out how to express a long
string that has that “printf” inside it, because the printf statement
itself has quotes, too. I just need the number to end up being
zero-padded to 3 characters. So, for “3,” I want “003.”
On Fri, Mar 02, 2007 at 12:39:13AM +0900, Peter B. wrote:
This is a pretty simple question. I need to do a “printf” of some
numbers inside a string. I just can’t figure out how to express a long
string that has that “printf” inside it, because the printf statement
itself has quotes, too.
I think what you were trying to do is:
number = “3”
puts “stuff, #{sprintf “%.3d”, number}”
Note that sprintf(…) is like printf(…) but returns the result as a
string
value, rather than sending it to stdout. Then #{} lets you insert an
arbitary expression inside another string.
But as pointed out by others, you can do this in one go as
Hi,
This is a pretty simple question. I need to do a “printf” of some
numbers inside a string. I just can’t figure out how to express a long
string that has that “printf” inside it, because the printf statement
itself has quotes, too. I just need the number to end up being
zero-padded to 3 characters. So, for “3,” I want “003.”
On Fri, Mar 02, 2007 at 12:39:13AM +0900, Peter B. wrote:
This is a pretty simple question. I need to do a “printf” of some
numbers inside a string. I just can’t figure out how to express a long
string that has that “printf” inside it, because the printf statement
itself has quotes, too.
I think what you were trying to do is:
number = “3”
puts “stuff, #{sprintf “%.3d”, number}”
Note that sprintf(…) is like printf(…) but returns the result as a
string
value, rather than sending it to stdout. Then #{} lets you insert an
arbitary expression inside another string.
But as pointed out by others, you can do this in one go as
printf “stuff, %.3d\n”, number
HTH,
Brian.
Thanks to all you guys. I’ll probably use sprintf, actually, now that
I’m clear about how it’s used.
Cheers.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.