Ruby/Class/Readable attributes

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

Перейти к: навигация, поиск

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