Ruby - redefining instance methods not working
My simple attempt to redefine instance methods are not working
class File
alias_method :old_atime, :atime
def atime(*args)
puts "helllllo"
old_atime(*args)
end
end
f = File.new("C:\\abc.txt","w")
puts f.atime
An开发者_如何学Pythony idea why?
I'm attempting to print "helllllo" everytime File#atime is called. Even alias old_atime atime
is not working.
Is there something I'm doing wrong here?
Above code works perfectly as it should be. Puts "helllllo" writes "helllllo" in to your opened file. Puts inside the file instance meant for writing.
Just call f.close and open your file in text editor. You can see the content.
Yep, Ramesh is right. Try this:
class File
alias_method :old_atime, :atime
def atime(*args)
Kernel.puts "helllllo" # <---- Kernel method
old_atime(*args)
end
end
f = File.new("C:\\abc.txt","w")
puts f.atime
The issue is that 'puts' is defined in File for writing to files. You want the Kernel one which is used unless defined in a more specific scope.
This should work fine, but IO#puts
writes to the IO
object itself, not STDOUT. In other words, it's writing to the file.
Call f.atime
a few times and then f.close
within irb
and you should see it printing helllllo
to the file for each call to atime
.
To print to STDOUT, you could use $stdout.puts
or Kernel.puts
.
精彩评论