[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

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

Andreas S

12/8/2006 10:42:00 PM




>From: Daniel Finnie <danfinnie@optonline.net>
>Reply-To: ruby-talk@ruby-lang.org
>To: ruby-talk@ruby-lang.org (ruby-talk ML)
>Subject: Re: beginner Q: Kernel#puts, STDOUT, $stdout relation
>Date: Sat, 9 Dec 2006 07:28:20 +0900
>
>Puts is a method of Kernel.
>

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?

_________________________________________________________________
Talk now to your Hotmail contacts with Windows Live Messenger.
http://clk.atdmt.com/MSN/go/msnnkwme0020000001msn/direct/01/?href=http://get.live.com/messenge...


1 Answer

Jacob Fugal

12/9/2006 12:08:00 AM

0

On 12/8/06, Andreas S <andreas_s@hotmail.com> wrote:
> >From: Daniel Finnie <danfinnie@optonline.net>
> >Reply-To: ruby-talk@ruby-lang.org
> >To: ruby-talk@ruby-lang.org (ruby-talk ML)
> >Subject: Re: beginner Q: Kernel#puts, STDOUT, $stdout relation
> >Date: Sat, 9 Dec 2006 07:28:20 +0900
> >
> >Puts is a method of Kernel.
>
> 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