Object Oriented Flashcards
class Person attr_accessor :name, :age end p = Person.new p.name = "Fred" p.age = 20 puts p.instance_variables
[“@age, @name”]
enscapsulation
Encapsulation is the ability for an object to have certain methods and attributes available for use publicly (from any section of code), but for others to be visible only withinthe class itself or by other objects of the same class.
class Person def anyone_can_access_this; ...; end def this_is_private; ...; end def this_is_also_private; ...; end def another_public_method; ...; end private :this_is_private, :this_is_also_private end
enscapsulate methods in one line
plymorphism
writing code that can work with objects of multiple types and classes at once.
a = Drawing.give_me_a_circle puts a.what_am_i a = Drawing::Circle.new puts a.what_am_i a = Circle.new puts a.what_am_i
This is a circle
This is a circle
NameError: uninitialized constant Circle
constants have scope within classes (t/f)
True Pi = 3.14 and Pi=3 in a class are different. class::Pi = 3 Pi = 3.14
Modules
provide a structure to collect Ruby classes, methods, and constants into a single,
separately named and defined unit
Namespaces
avoid name-related clashes.
name conflict
As the last file loaded, it turns out to be the latter version of random, and a random letter
should appear onscreen. Unfortunately, however, it means your other randommethod has
been “lost.”
This situation is known as a name conflict,
module NumberStuff def NumberStuff.random rand(1000000) end end module LetterStuff def LetterStuff.random (rand(26) + 65).chr end end puts NumberStuff.random puts LetterStuff.random
value varies from 0 - 999999 and char from A-Z
modules benefits
help solve conflicts providing namespaces that contain any number of classes, methods, and constants, and allow you to address them directly. Modules simply provide ways to organize methods, classes, and constants into separate namespaces.
modules are classes (t/f)
False. you cannot define instances of a module, nor inherit from them.