DevHeads.net

print vs puts handling of $_

'print' seems to handle $_ differently 'puts':

fh = open './file.txt'
while fh.gets
print if ~ /\b\w{2}\b/
end

;=> prints matching lines

fh = open './file.txt'
while fh.gets
puts if ~ /\b\w{2}\b/
end

;=> prints a blank line for every matching line

fh = open './file.txt'
while fh.gets
puts $_ if ~ /\b\w{2}\b/
end

;=> prints matching lines

A bit inconsistent?

gvim

Comments

Re: print vs puts handling of $_

By Abinoam Jr. at 01/20/2014 - 11:18

Dear gvim,

I think this was the intended behavior.

Kernel#print
If no arguments are given, prints $_.
<a href="http://ruby-doc.org/core-2.1.0/Kernel.html#method-i-print" title="http://ruby-doc.org/core-2.1.0/Kernel.html#method-i-print">http://ruby-doc.org/core-2.1.0/Kernel.html#method-i-print</a>

IO#puts
If called without arguments, outputs a single record separator.
<a href="http://www.ruby-doc.org/core-2.1.0/IO.html#method-i-puts" title="http://www.ruby-doc.org/core-2.1.0/IO.html#method-i-puts">http://www.ruby-doc.org/core-2.1.0/IO.html#method-i-puts</a>

Abinoam Jr.

On Sat, Jan 18, 2014 at 4:47 PM, gvim < ... at gmail dot com> wrote:

Re: print vs puts handling of $_

By Ryan Davis at 01/18/2014 - 17:47

10002 % ri IO.puts
= IO.puts

(from ruby core)
Writes the given objects to ios as with IO#print. Writes a record
separator (typically a newline) after any that do not already end with a
newline sequence. If called with an array argument, writes each element on a
new line. ***If called without arguments, outputs a single record separator.***

Using implicit $_ is generally considered bad style.