Ruby/Class/Readable attributes

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

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

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

Creating Readable Attributes

# object. color here (as in animal.color) is called an attribute.
# color is a readable attribute because you can read the value of the internal @color instance variable.
class Animal
  def color()
    @color
  end
  def initialize(color)
    @color = color
  end
end
animal = Animal.new("brown")
puts "The new animal is " + animal.color



Ruby makes creating readable attribute easier with attr_reader

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