Ruby Fundamentals: Properties & Variables
What This Tutorial Covers
Instance Variables
@-prefixed state held by each object.
Attr Accessors
Auto-generate getters and setters.
Property Access
Encapsulation through method-based access.
Noble Desktop's Full-Stack Web Development Certificate teaches modern web development concepts that transfer across Ruby, Python, and JavaScript stacks.
Dive into the finer aspects of coding with Ruby on Rails in this detailed tutorial, covering everything from properties of objects, to working with instance and local variables, including practical exercises to help solidify your knowledge and understanding.
Topics Covered in This Ruby on Rails Tutorial:
Properties of Objects, Instance Variables & Local Variables, Global Variables
Exercise Overview
In this exercise, you’ll continue learning Ruby fundamentals. Specifically you will learn more about using properties. Properties are like adjectives, describing or giving more information about the object. You’ll also learn more about using variables to store information.
Properties of Objects
Objects do not simply perform actions; they have properties too. Cats do not just swipe fish and claw furniture, but have names and coat colors too. Properties of an object are like a variable that is attached to the object. We’ve been referring to our cats as fluffy and george, but they don’t think of themselves that way—at least, not yet. Those are variable names, not proper names.
If you closed Terminal, closed the window or exited IRB, open a Terminal window and type the
irbcommand.Type the following:
class Cat def initialize(name) @name = name end def say_name @name end fluffy = Cat.new("Miss Fluffy") fluffy.say_name george = Cat.new("Mr George") george.say_nameWe have just added proper names (Miss Fluffy and Mr George) to the two instances of the Cat class (fluffy and george). They will now be able to tell us their own names. Let’s unpack what we just typed:
- We defined
initializeas a special method that is automatically called whenever an object is created. When we create new instances of the Cat class we pass in a name. In other words, cats are now born with a name. - In the piece of code
initialize(name), the information in parentheses is a parameter. It signifies that the method is expecting some input—in this case, the name for a new cat.
- We defined
Attempt to create a new cat without naming it. Type the following:
roger = Cat.newTerminal will return an error message, because the method is expecting input in the
(name)parameter, and we haven’t properly assigned a name to the cat Roger. Let’s create a default value, so even if a cat isn’t assigned a name at birth, we can still refer to it as “Kitty.”Type the following to create a default name value:
class Cat def initialize(name = "Kitty") @name = name endTest out the newly created default value by typing the following:
roger = Cat.newGreat! This time, there is no error message like there was when we typed the same exact thing a moment ago. But does Roger know his own name?
Ask the newly created cat, Roger, his name by typing the following:
roger.say_nameWhen we ask Roger to say his name, he says
"Kitty"because we haven’t properly named him Roger, but we have defined a default value(name = "Kitty")that will apply to all cats who aren’t assigned names at birth.Just because we now have a default value in place, of course, we aren’t prevented from naming cats. Check that we can still name cats by typing:
sophie = Cat.new("Miss Sophie") sophie.say_nameWe can see that Miss Sophie knows her name, and that the default value
"Kitty"will only appear in the event we have an unnamed cat.
Instance Variables & Local Variables
In the variable @name the @ sign makes this an instance variable. There are also local variables which do not have an @ sign. Here’s the difference:
- Instance variables (@ sign) can be accessed by any method throughout the class.
- Local variables (no @ sign) can only be accessed from within its own method.
Let’s see them in action so we can understand this concept better.
They say you can’t teach a cat, but hey, let’s try! Type the following:
class Cat def learn_stuff @remember_this = "location of tuna can" forget_this = "how to catch a mouse" "I learned stuff!" endNOTE: You have just created an instance variable
@remember_thisand a local variableforget_this. They are easy to distinguish by the respective presence and absence of @ signs. In this case,"I learned stuff!"is the return value.Let’s create a couple of functions so we can check in on the values of our instance variable and local variable a bit later. Type the following:
def what_did_you_remember? @remember_this end def what_did_you_forget? forget_this endNOTE: Ruby variables are allowed to end in a question mark, as above. The question mark doesn’t add any extra features, but makes your code a bit more readable.
Type the following:
fluffy.learn_stuff fluffy.what_did_you_remember?Look at the result! Fluffy has learned stuff and remembered the location of the tuna can, which we introduced in the
@remember_thisinstance variable. Because@remember_thisis an instance variable, with an @ sign before it, we were able to define it with one method and access it with a different method later.Let’s contrast this with the behavior of local variables by typing the following:
fluffy.what_did_you_forget?Terminal should return an error that says
NameError: undefined local variable or method 'forget_this'. This error demonstrates that a local variable created with one method cannot be called by a different method. Hopefully this can help you see the difference between instance variables and local variables. It may be hard at this point to understand how this is used in the real-world. Later when you get to Rails you’ll see instance that variables are often used to share data between controllers and views.