调用setter函数ruby(请参阅fname =(fname)之后的注释] [duplicate](calling setter function ruby (see comment after fname=(fname) [duplicate])
这个问题在这里已有答案:
为什么Ruby setter在课堂上需要“自我”资格? 3个答案 Ruby - 从对象内部调用setter [复制] 1个答案 #Creating a class that will count words in any object file class File_handling attr_reader :fname def initialize(fname) #@fname = fname if File.exist? fname @fname = fname else fname=(fname)#why this doesnt work to call the function below end end def fname=(finame) if File.exist? finame @fname = finame else p "Enter a good file name >>> " filename = gets.chomp @fname=(filename) end end def printfile() File.foreach(@fname) do |line| puts line.chomp end end end f1 = File_handling.new('text.txt') f1.printfile() def printfiles(fname) File.foreach(fname) do |line| puts line end end p printfiles('test.txt')我是Ruby的新手并试图了解一些事情。 我还没有真正完成课程,但我想知道为什么调用上面的fname =函数不起作用无论我输入什么文件名,我都不会收到else消息
This question already has an answer here:
Why do Ruby setters need “self.” qualification within the class? 3 answers Ruby - Calling setters from within an object [duplicate] 1 answer #Creating a class that will count words in any object file class File_handling attr_reader :fname def initialize(fname) #@fname = fname if File.exist? fname @fname = fname else fname=(fname)#why this doesnt work to call the function below end end def fname=(finame) if File.exist? finame @fname = finame else p "Enter a good file name >>> " filename = gets.chomp @fname=(filename) end end def printfile() File.foreach(@fname) do |line| puts line.chomp end end end f1 = File_handling.new('text.txt') f1.printfile() def printfiles(fname) File.foreach(fname) do |line| puts line end end p printfiles('test.txt')I'm new to Ruby and trying to understand a few things. I'm not really finished with the class but I would like to know why calling the fname= function above does not work I never get the else message no matter what file name I enter
最满意答案
因为解释器会认为您要将局部变量fname的值赋给局部变量fname 。 为了使它工作,你必须更明确:
self.fname = fnameBecause the interpreter will think you want to assign the value of the local variable fname to the local variable fname. To make it work, you have to be more explicit:
self.fname = fname更多推荐
发布评论