What Do Ruby's Printf Arguments Mean

What do Ruby's printf arguments mean?

For syntax look at any printf docs, but check the sprintf docs on ruby-doc.

They're separated by commas because they're separate parameters to the function, but that's more or less syntactic sugar. Think varargs.

Not sure what you mean with the %s\n thing, it's a string then a newline: that's what it outputs.

If your question is specifically "how does the code turn a formatting string and a group of arguments into output" I'd probably search for source, for example, a tiny embedded printf. Nutshell version is that the format string is searched for formatting options, they consume their associated parameters, outputting an appropriately-formatted string. It's a tiny little DSL.

Ruby printf output explained

why it equates to 1032

It does not. What it does, it prints number 10 and then, immediately after, number 32 (result of 3 * 10 + 2).

It is paramount to learn to distinguish the two: actual value of an expression and its side-effect (text printed to console, in this example).

I'm especially interested in understanding the modulos and the d and \n

Those are not modulos. %d is a format specifier. Means "print an integer here". Read up on sprintf.

How do I properly escape % in call to printf in Ruby?

You should pass value as an argument to printf

printf "To have a 60%% test average, your final exam must be at least %0.2f.\n",value

Output format using printf?

You can use regex replace as well to have this.

input = [
'tomcat7.0 Build-Date: 20140220-1147',
'tomcat7.1 Build-Date: 20140220-1147',
'tomcat7.2 Build-Date: 20140220-1147',
'tomcat7.3 Build-Date: 20140220-1147'
]

input.each{ |x| puts x.gsub(/(.*?)\s+Build-Date:\s+(.*)/, "\\1\t\\2")}

Ruby String Output

You can use the various methods available in the String class.

input1 = 'one'
input2 = 'two'
input3 = 'three'

input1 = input1.ljust 10
#=> "one "
input2 = input2.center 7 #credit to user Simple Lime
#=> " two "
input3 = input3.rjust 10
#=> " three"

puts output = input1 + ' ' + input2 + ' ' + input3
#one two three
output.size
#=> 31

What is p in Ruby?

p() is a Kernel method

It writes obj.inspect to the standard output.

Because Object mixes in the Kernel module, the p() method is available everywhere.

It's common, btw, to use it in poetry mode, meaning that the parens are dropped. The CSV snippet can be written like...

CSV.open 'data.csv', 'r' do |row|
p row
end

It's documented here with the rest of the Kernel module.



Related Topics



Leave a reply



Submit