- Name what each of the below is:
a = 1
# => ex. a is a local variable, and is a Fixnum object with value 1
@a = 2
# => @a is an instance variable, and is a Fixnum object with value 2
user = User.new
# => user is a new instance object of the class User
user.name
# => the object user is calling the name getter instance method
user.name = "Joe"
# => the object user is calling the name setter instance method, resetting the object's name string value to "Joe"
-
How does a class mixin a module?
module ModExample # code for module here end class Animal include ModExample # code for class here end
-
What's the difference between class variables and instance variables?
Answer: A class variable is shared among the class and all of its descendants. It also begins with two @@ symbols. An instance variable is not shared by the class' descendants and it begins with one @ symbol.
-
What does
attr_accessor
do?Answer:
attr_accessor
is a shortcut to define a class' getter and setter methods.class Dog attr_accessor :name end # This is the same without using 'attr_accessor'. class Dog def name @name end def name=(new_name) @name = new_name end end
-
How would you describe this expression:
Dog.some_method
Answer: The class
Dog
is calling a class method calledsome_method
. -
In Ruby, what's the difference between subclassing and mixing in modules?
Answer:
Subclassing is when the classes is a relationship and has a single inheritance. For example, a Dog subclass will inherit all of the behaviors of an Animal superclass.
Mixing in modules is called composition and it is when classes has a relationship. This is usually when classes have multiple inheritances or when certain behaviors are shared among classes, but not every single one of them.
-
Given that I can instantiate a user like this:
User.new('Bob')
, what would theinitialize
method look like for theUser
class?class User attr_accessor :name def initialize(name) self.name = name end end
-
Can you call instance methods of the same class from other instance methods in that class?
Answer: Yes, you may call instance methods of the same class from other methods in that class.
-
When you get stuck, what's the process you use to try to trap the error?
Answer: Use the
pry
gem to debug your code. Insertbinding.pry
to each of the sections in your code that you wish to debug. Trap the error by eliminating the non-problematic areas.require "pry" # Ruby code # Ruby code
binding.pry