Final Project - instance variables


#1

Why do we have to use “@” in the “show” and “write_to_file” methods and nowhere else?

    class List
      attr_reader :all_tasks

      def initialize
        @all_tasks = []
      end

      def add(task)
        all_tasks << task
      end

      def delete(task_number)
        all_tasks.delete_at(task_number - 1)
      end

      def update(task_number, task)
        all_tasks[task_number - 1] = task
      end

      def show
        @all_tasks.map.with_index { |l, i| "(#{i.next}): #{l}" }
      end

      def write_to_file(filename)
        machinified = @all_tasks.map(&:to_machine).join("\n")
        IO.write(filename, machinified)
      end

      def read_from_file(filename)
        IO.readlines(filename).each do |line|
          status, *description = line.split(':')
          status = status.include?('X')
          add(Task.new(description.join(':').strip, status))
        end
      end
    end

#2

always refers to the instance in the current context.

my_list = List.new
my_list.add('read docs')
my_list.show

When the two methods are called on my_list, @ represents that object context, specifically.


#3

Thanks for your reply, this makes sense, but what confuses me is that I could use:
def show
@all_tasks.map.with_index { |l, i| “(#{i.next}): #{l}” }
end
but also:
def show
all_tasks.map.with_index { |l, i| “(#{i.next}): #{l}” }
end
And it doesn’t make a difference, so I am wondering why the “@” was used in that method?


#4

How are you calling the method?


#5

instance_name.show

      if __FILE__ == $PROGRAM_NAME
        include Menu
        include Promptable
        ml = List.new
        puts 'Please choose from the following list'
        until ['q'].include?(user_input = prompt(show).downcase)
          case user_input
          when '1'
            ml.add(Task.new(prompt('What is the task you would like 
            to accomplish?')))
          when '2'
            puts ml.show
          when '3'
            ml.update(prompt('Which task to update?').to_i, 
            Task.new(prompt('Task Description?')))
          when '4'
            puts ml.show
            ml.delete(prompt('Which task to delete?').to_i)
          when '5'
            ml.write_to_file(prompt 'What is the filename to 
            write to?')
          when '6'
            begin
              ml.read_from_file(prompt('What is the filename to 
              read from?'))
            rescue Errno::ENOENT
              puts 'File name not found, please verify your file 
              name and path.'
            end
          else
            puts 'Try again, I did not understand.'
          end
          prompt('Press enter to continue', '')
        end
        puts 'Outro - Thanks for using the awesome menu system!'
      end