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

On Jan 18, 2014, at 11:47, gvim [email protected] wrote:

while fh.gets
;=> prints matching lines

A bit inconsistent?

10002 % ri IO.puts
= IO.puts

(from ruby core)

ios.puts(obj, …) -> nil


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.

Dear gvim,

I think this was the intended behavior.

Kernel#print
If no arguments are given, prints $_.
http://ruby-doc.org/core-2.1.0/Kernel.html#method-i-print

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

Abinoam Jr.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs