Classes and objects
| Define a class | |
| Initialize objects | |
| attr_reader and accessor | |
| What self is |
Define a class
A class is a blueprint for objects. It groups data and behavior in one named place, so related methods live next to the values they use.
Shared behavior can also come from outside the class, as shown in
Modules and mixins.
class User
def hello
puts "Hello"
end
end
user = User.new
user.hello
Initialize objects
When you call new, Ruby builds a fresh object and runs a special method named initialize. It receives the arguments you pass to new and stores them in instance variables that start with @.
Each object keeps its own copy of these variables, so two users never share a name.
class User
def initialize(name)
@name = name
end
def hello
puts "Hello, " + @name
end
end
user = User.new("Ada")
user.hello
attr_reader and accessor
Instance variables hide inside the object. To read them from outside, declare attr_reader with the variable name without @.
Use attr_accessor when outside code must also change the value. Prefer the reader by default and open writing only where needed.
class User
attr_reader :name
attr_accessor :email
def initialize(name)
@name = name
end
end
user = User.new("Ada")
puts user.name
What self is
Inside a method, self is the current object, the one that received the call. You can call other methods on it or print it for inspection.
At the top level of a program self is a plain object called main, which is why small scripts can call methods without a receiver.
class Counter
def show_self
puts self
end
end
Counter.new.show_self
Next: Inheritance
Article author: Arthur Isaev