Ruby: Classes, Instance/Class Variables and Methods

Ruby: Classes, Instance/Class Variables and Methods

memorize.aimemorize.ai (lvl 286)
Section 1

Preview this deck

Can class methods access instance variable and methods?

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

0

All-time users

0

Favorites

0

Last updated

6 years ago

Date created

Mar 1, 2020

Cards (12)

Section 1

(12 cards)

Can class methods access instance variable and methods?

Front

No. class methods, because they're called by a class and not an instance, obviously cannot access any instance variables or instance methods.

Back

Instantiating class instances

Front

You use a special new method to do that. new is a Class Method, which means that you call it on the class (in this case Array) and not the specific instance of that class.When you call that method, it creates a new instance (object) of that class and then runs a special method inside the class called initialize

Back

Instance Variable

Front

You designate an instance variable using the @variable_name notation. You will usually set up the instance variables for the first time in your initialize method so they're ready for you right away. Allows objects of the same class to have different values.

Back

How to edit instance variable of a object

Front

You need to create a setter method, which is similar syntax to the getter but with an equals sign and an argument. Ex: def health=(new_health) @health = new_health end

Back

A key Value pair

Front

Hash

Back

How to define a class method

Front

~By preceding its name with self (e.g. def self.class_method). ~Using the name of the class (e.g. def Viking.class_method)

Back

When to use a class

Front

~Your objects start needing functionality of their own (e.g. methods). ~Multiple objects need access to the same general behavior. ~You want multiple copies of the same object to each have their own individual attributes and state (instance variables).

Back

How to view instance variable of a object

Front

Create a method specifically to get that variable, called a getter method, and just name it the same thing as the variable you want. Ex: def health @health # Implicitly returned end

Back

Accessing Instance Variable from within class

Front

Because of your getters and setters, there are two different ways to access. ~Calling it normally using @instance_name. ~Calling the getter or setter method on the instance using 'self'.

Back

Instance Methods

Front

These methods get called on an individual instance of the class.

Back

attr_accessor

Front

helper method creates those getters and setters. Just pass it the symbols for the variables you want to make accessible. Ex: class Viking attr_accessor :name, :age, :health, :strength end

Back

Class Variable

Front

denoted with @@. owned by the class itself so there is only one of them shared among all the instances instead of one per instance.

Back