beginner Q: Kernel#puts, STDOUT, $stdout relation

A

Andreas S

Can anybody help me understanding the relation between Kernel#puts, STDOUT
and $stdout?

I thought 'puts' is equivalent to '$stdout.puts'. Why 'puts' doesn't give
same result as 'STDOUT.puts'?

class << STDOUT
def puts(*args)
args[0] = "I say " + args[0] unless args.empty?
super(args)
end
end

puts "hello"
STDOUT.puts "hello"
$stdout.puts "hello"
=> hello
I say hello
I say hello


Thank you in advance
-andre

_________________________________________________________________
Talk now to your Hotmail contacts with Windows Live Messenger.
http://clk.atdmt.com/MSN/go/msnnkwm.../?href=http://get.live.com/messenger/overview
 
J

Jacob Fugal

But, doesn't it depend on what IO object $stdout holds? I redefined $stdout
'puts' function, but why it does not affect Kernel's puts method?

It's a tricky relationship, and I'm not quite sure how or why it works
this way, but Kernel#puts does not use STDOUT's (or $stdout, they can
be different) puts. It does use STDOUT/$stdout (I'm not really sure
which) but IIRC Kernel#puts is implemented directly using the write
method. Caveat here though -- the write method is called *twice*, once
for the argument, then again for the newline. So modifying your source
to rewrite "write" instead of "puts":

class << STDOUT
def write(*args)
args[0] = "I say " + args[0] unless args.empty?
super(args)
end
end

puts "hello"
STDOUT.puts "hello"
$stdout.puts "hello"

produces:

$ ruby test.rb
I say helloI say
I say helloI say
I say helloI say

Jacob Fugal
 
E

Eric Hodel

Can anybody help me understanding the relation between Kernel#puts,
STDOUT and $stdout?

I thought 'puts' is equivalent to '$stdout.puts'. Why 'puts'
doesn't give same result as 'STDOUT.puts'?

class << STDOUT
def puts(*args)
args[0] = "I say " + args[0] unless args.empty?
super(args)
end
end

puts "hello"

This calls $stdout.write "hello\n"
STDOUT.puts "hello"
$stdout.puts "hello"
=> hello
I say hello
I say hello

PS:

Please mess with $stdout, not STDOUT, if at all possible.

http://blog.segment7.net/articles/2006/08/17/stdout-vs-stdout
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,052
Latest member
LucyCarper

Latest Threads

Top