Ruby/Class/initialize class

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

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

Содержание

Define constructor for a class

#!/usr/bin/env ruby
class Hello
  def initialize( hello )
    @hello = hello
  end
  def hello
    @hello
  end
end
salute = Hello.new( "Hello, myValue!" )
puts salute.hello



initializes the instance variable @name with the standard initialize method.

class Horse
  def initialize( name )
    @name = name
  end
  def horse_name
    @name
  end
end
horse = Horse.new( "Doc Bar" )
puts horse.horse_name # => Doc Bar



Initialize three attributes

class Person
  attr_reader :name, :age, :occupation
  def initialize(name, age, occupation)
    @name, @age, @occupation = name, age, occupation
  end
  def isIn?
    true
  end
end
jimmy = Person.new("J", 21, "reporter")
clark = Person.new("C", 35, "reporter")
jimmy.isIn?                                     # => true
clark.isIn?                                     # => true



the code adds an instance variable named @color that stores the color of the animal to the initialize method:

class Animal
  def initialize
    @color = "red"
  end
end



This code starts by creating the Animal class, and then adds a method named initialize:

# In Ruby, the initialize method is called automatically when you use a class to create an object. 
class Animal
  def initialize
  end
end