[ next ] [ prev ] [ contents ] [ up to Ruby Immersion ] Using Ruby

Attributes

class FileInstaller
  def file
    @file
  end
  def target_dir
    @target_dir
  end
  def target_dir=(new_target_dir)
    @target_dir = new_target_dir)
  end
  # ... other code ...
end

fi = FileInstaller.new("a", "b")
fi.name              # => a
fi.target_dir        # => b
fi.target_dir = "c" 
fi.target_dir        # => c

  • Instance variables (e.g. @name) are always private. (All interaction with an object has to be through a message/method.)

  • Write getters/setters to access

  • Tedious to write

class FileInstaller
  attr_reader :file
  attr_accessor :target_dir
  # ... other code ...
end

  • attr_reader :name writes a getter for name.

  • attr_accessor :name writes a getter and setter for name.


[ next ] [ prev ] [ contents ] [ up to Ruby Immersion ] Copyright 2003 by Jim Weirich.
Some Rights Reserved