Ruby - 重新定义实例方法不起作用
我重新定义实例方法的简单尝试不起作用
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
知道为什么吗?
我试图在每次调用 File#atime 时打印“helllllo”。甚至 alias old_atime atime
也不起作用。
我在这里做错了什么吗?
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
Any 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
上面的代码可以完美地工作。 Puts “helllllo” 将“helllllo”写入您打开的文件中。放入用于写入的文件实例中。
只需调用 f.close 并在文本编辑器中打开文件。就可以看到内容了。
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.
是的,拉梅什是对的。试试这个:
问题是“puts”在 File 中定义用于写入文件。您需要使用除非在更具体的范围中定义的内核。
Yep, Ramesh is right. Try this:
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.
这应该可以正常工作,但是
IO#puts
写入IO
对象本身,而不 STDOUT。换句话说,它正在写入文件。调用
f.atime
几次,然后在irb
中调用f.close
,您应该会看到它打印helllllo
到每次调用atime
的文件。要打印到 STDOUT,您可以使用
$stdout.puts
或Kernel.puts
。This should work fine, but
IO#puts
writes to theIO
object itself, not STDOUT. In other words, it's writing to the file.Call
f.atime
a few times and thenf.close
withinirb
and you should see it printinghelllllo
to the file for each call toatime
.To print to STDOUT, you could use
$stdout.puts
orKernel.puts
.