【问题标题】:calling setter function ruby (see comment after fname=(fname) [duplicate]调用 setter 函数 ruby​​(参见 fname=(fname) [重复] 之后的注释
【发布时间】:2015-12-29 15:53:32
【问题描述】:
#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 消息

【问题讨论】:

    标签: ruby


    【解决方案1】:

    因为解释器会认为你想将局部变量fname的值赋给局部变量fname。为了让它发挥作用,你必须更加明确:

    self.fname = fname
    

    【讨论】:

    • 谢谢,让我明白调用setter函数我必须使用self.[function]。这与其他语言有点不同,但感谢您的快速回复
    • @yveskas,在课堂上——是的。在外部,您可以在手头的实例上调用它。在其他语言中,您通常会使用 setVariable 之类的内容,因此如果这是局部变量赋值或调用 setter,编译器/解释器不会感到困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2021-12-29
    • 1970-01-01
    相关资源
    最近更新 更多