Ruby/Class/Writable Attributes

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

(Различия между версиями)
Перейти к: навигация, поиск
м (1 версия: Импорт выборки материалов по Ruby)
 

Текущая версия на 17:55, 13 сентября 2010

Creating Writable Attributes: using an accessor method followed with an equals sign (=)

class Animal
  attr_reader :color
  def color=(color)
    @color = color
  end
  def initialize(color)
    @color = color
  end
end
animal = Animal.new("brown")
puts "The new animal is " + animal.color
animal.color = "red"
puts "Now the new animal is " + animal.color



Ruby gives you a quick way to create writable attributes with attr_writer

class Animal
  attr_reader :color
  attr_writer :color
  def initialize(color)
    @color = color
  end
end
animal = Animal.new("brown")
puts "The new animal is " + animal.color
animal.color = "red"
puts "Now the new animal is " + animal.color