Ruby/Class/attr writer

Материал из Wiki.crossplatform.ru

Версия от 17:10, 26 мая 2010; (Обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Defining and Using an Employee Class

require "date"
class Employee
  attr_reader :name, :hiredate, :salary
  attr_writer :salary
  def initialize(n, h, s)
    @name = n
    @hiredate = h
    @salary = s
  end
end
a_date = Date.new(2006, 6, 21)
me = Employee.new("Barry Burd", a_date, 1000000.00)
a_date = Date.new(2006, 6, 25)
you = Employee.new("Harriet Ritter", a_date, 50000.00)
print me.name
printf("\t%s\t%5.2f\n", me.hiredate, me.salary)
print you.name
printf("\t%s\t%5.2f\n", you.hiredate, you.salary)
me.salary += 1000.00
print me.name
printf("\t%s\t%5.2f\n", me.hiredate, me.salary)



Readable attribute and writable attribute

class Employee
 attr_reader :name
 attr_accessor  :title, :salary
 def initialize( name, title, salary )
   @name = name
   @title = title
   @salary = salary
 end
end
fred = Employee.new("Fred", "Operator", 30000.0)
fred.salary=35000.0



Using attr_writer :color is the same as if you had done this:

class Animal
  attr_reader :color
  attr_writer :color
  def initialize(color)
    @color = color
  end
end
class Animal
  attr_reader :color
  def color=(color)
    @color = color
  end
  def initialize(color)
    @color = color
  end
end