0
#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

ndnenkov
  • 35,425
  • 9
  • 72
  • 104
yveskas
  • 35
  • 1
  • 6

1 Answers1

0

Because 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
ndnenkov
  • 35,425
  • 9
  • 72
  • 104
  • Thanks, so let me understand to call setter function I have to use self.[function]. that's a bit different than other languages, but thank you for the quick reply – yveskas Dec 29 '15 at 07:58
  • @yveskas, in the class itself - yes. Outside, you can call it on the instance at hand. In other languages you often have something like `setVariable` so the compiler/interpreter doesn't get confused if this is local variable assignment or calling a setter. – ndnenkov Dec 29 '15 at 07:59