Ruby Classes
A class is a blueprint for objects. Each object made from a class holds its own values and runs the methods written in the class.
A class and one object
initialize stores the given name in @name. The greet method reads @name and prints the line.
class Dog
def initialize(name)
@name = name
end
def greet
puts "#{@name} says hello"
end
end
dog = Dog.new("Rex")
dog.greetTwo objects, separate values
Both dogs come from the Dog class. Each new call stores a different name, and each greet line shows its own name.
class Dog
def initialize(name)
@name = name
end
def greet
puts "#{@name} says hello"
end
end
rex = Dog.new("Rex")
bella = Dog.new("Bella")
rex.greet
bella.greetTwo values stored at the start
initialize takes a name and an age here. profile reads both values from its object.
class Dog
def initialize(name, age)
@name = name
@age = age
end
def profile
puts "#{@name} is #{@age} years old"
end
end
dog = Dog.new("Rex", 3)
dog.profileExample
class Dog
def initialize(name, age)
@name = name
@age = age
end
def greet
puts "#{@name} says hello"
end
def profile
puts "#{@name} is #{@age} years old"
end
end
rex = Dog.new("Rex", 3)
bella = Dog.new("Bella", 5)
rex.greet
rex.profile
bella.greet
bella.profileKey points
- The word class starts a class, and the word end closes it.
- A class name starts with a capital letter.
- new builds one object from a class.
- initialize runs when new builds an object.
- initialize stores starting values in names that begin with @.
- A method inside the class reads the @ names of its own object.
- Each object keeps its own values for its @ names.
In this example, the Dog class stores a name and an age in initialize. greet and profile read those values from their own object. Rex and Bella each print their own lines, so the two objects hold separate values.
Note
Code never calls initialize by name, because new runs it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which method runs when a new object is built with new?