Classes Objects and Variables

Key Concepts

Variables

You can not set the scope or the type. i.e. const or String of a variable. variables are private by default

def foo_assignment
    # Can only be accessed in method
    foo = "bar"
    foo
end

Objects

A number, boolean and string are all objects in Ruby


def class_example
    {
        string: "foo".class,
        also_string: (String.new("foo")).class,
        number: 3.class,
        bool: false.class
    }
end

The above is shorthand syntax for creating the object and initializing it with a value. The string object provides a constructor which is an alias

When assigning an object to a variable the variable holds a reference to the object. It does not create a new object with the same value

def same_object(a)
    b = a # reference the same object
    b # just a reference to a
end

def clone_object(a)
    b = a.clone # make a copy of the object
    b # This is not a
end

Note that the .clone method is a shallow copy, nested references do not get copied as values then get copied as references

Each object created inherits a large amount of library methods. The official API documentation: https://ruby-doc.org/stdlib-2.5.3/.

TL;DR

Sites

Pragmatic Ruby - classes, variables and methods Ruby Monk - objects chapter

Videos

Ruby Fundamentals - variables, nil, methods and scope

Challenge 🎠

Use Rspec to run the challenges

bin/rspec spec/challenges/objects-variables_spec.rb --format doc

fix ../lib/challenges/objects-variables.rb so the tests pass ✔️

Go to next challenge

Classes