How to reopen the puts method

A

Adam Lauper

I am looking for some additional detail regarding the puts method. Hows
does the basic puts method work?

module Kernel
def self.puts text
$stdout.puts "New_Text"
end
end

# the following code doesn't actually call the Kernel puts method I've
redefined.
puts "Hello, World!"

# however, this code does.
Kernel.puts "Hello, World!"

I would like to insert a debug flag into the basic puts method and
suppress the output unless a flag is true. Something like this...
(except this doesn't work)

module Kernel
def self.puts text, debug=false
$stdout.puts text if debug
end
end

puts "Hello, World!", true

Any ideas?
 
P

pharrington

I am looking for some additional detail regarding the puts method.  Hows
does the basic puts method work?

module Kernel
  def self.puts text
    $stdout.puts "New_Text"
  end
end

# the following code doesn't actually call the Kernel puts method I've
redefined.
puts "Hello, World!"

# however, this code does.
Kernel.puts "Hello, World!"

I would like to insert a debug flag into the basic puts method and
suppress the output unless a flag is true.  Something like this...
(except this doesn't work)

module Kernel
  def self.puts text, debug=false
    $stdout.puts text if debug
  end
end

puts "Hello, World!", true

Any ideas?


You're creating a new Kernel.puts module method; you want to redefine
the Kernel#puts instance method.
 
A

Aldric Giacomoni

Adam said:
module Kernel
def self.puts text, debug=false
$stdout.puts text if debug
end
end

puts "Hello, World!", true

Any ideas?

You want to:
1) open Kernel
2) alias "puts" to something else, like "old puts"
3) define your own puts with your own input
4) call the old puts method when you're happy with the input
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top