Aaron Thomas
Aaron Thomas

Reputation: 5281

Sprintf versus Puts in Ruby

Why does sprintf not output in a function, but puts will?

irb(main):001:0> 3.times {|i| sprintf("%s", i.to_s)}
=> 3
irb(main):002:0> 3.times {|i| puts i}
0
1
2
=> 3

The documentation for puts says it goes to stdout. Why would sprintf not also go to stdout?

Using Ruby 2.5.0.

Upvotes: 1

Views: 4836

Answers (1)

spike
spike

Reputation: 10004

sprintf returns the formatted string, rather than printing it anywhere. Check out http://ruby-doc.org/core/Kernel.html#method-i-sprintf for the documentation.

You might be looking for printf instead.

Upvotes: 12

Related Questions