Ruby: Classes Flashcards

1
Q

How do you define a ruby class?

A

class NameOfClass

end

A ruby class is written with a capital first letter and written in CamelCase.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you create a new instance of a class?

A

We can create new instances of this class using new:

NameOfClass.new

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you mixin a module into a class?

A

You can include a module within a class definition. When this happens, all the module’s instance methods are suddenly available as methods in the class as well. They get mixed in. In fact, mixed-in modules effectively behave as superclasses. You must load or require the file before using include.

Example:

module Debug
      def who_am_i?
"#{self.class.name} (\##{self.object_id}): #{self.to_s}" end
    end
    class Phonograph
      include Debug
# ... end
    class EightTrack
      include Debug
      # ...
end
ph = Phonograph.new("West End Blues")
et = EightTrack.new("Surrealistic Pillow")

ph. who_am_i? # => “Phonograph (#330450): West End Blues”
et. who_am_i? # => “EightTrack (#330420): Surrealistic Pillow”

By including the Debug module, both the Phonograph and EightTrack classes gain access to the who_am_i? instance method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly