Explore core Object-Oriented Programming (OOP) concepts in Ruby, from classes and objects to inheritance and polymorphism. Learn how to structure your Ruby applications with these essential OOP principles.
objectdefclassmodulenew ClassName()ClassName.newobject.new ClassName()new ClassNameinitialize()new()start()create()object.variable_nameobject.get_variable_nameobject.variable_name()object.@variable_namenilobject.classclass(object)object.instance_of?object.define_class@ before the variable name$ before the variable name@ before the method name@@ before the variable namedef method_namemethod method_namedef method_name()function method_name()nildef variable_namedef get_variable_namedef variable_name()def variable_name; end@ before the variable name@@ before the variable name$ before the variable nameclass_variable syntaxclass_methoddefselfstaticclass MyClass @@class_variable = 5 def self.print_class_variable puts @@class_variable end end MyClass.print_class_variable
nil5MyClassErrordef MyClass.method_namedef self.method_namedef method_name(self)def method_name::self@@variable_name@variable_namevariable_nameself.variable_nameclass SubClass < SuperClassclass SubClass() inherits SuperClassclass SubClass from SuperClassclass SubClass: SuperClasssuperparentclassselfsuper()parent()call_super()super_method()| Qno | Answer |
|---|---|
| 1 | b) Data is organized around objects and classes |
| 2 | d) Compilation |
| 3 | b) Hiding data within objects and restricting access |
| 4 | a) To avoid code repetition by reusing properties and methods |
| 5 | a) Different methods having the same name but different implementations |
| 6 | c) class |
| 7 | b) ClassName.new |
| 8 | b) To initialize objects of a class |
| 9 | a) initialize() |
| 10 | a) object.variable_name |
| 11 | a) Ruby will search for it in the parent class |
| 12 | a) object.class |
| 13 | d) A variable that is unique to each object of a class |
| 14 | a) By using @ before the variable name |
| 15 | b) It will return nil |
| 16 | a) Getter and setter methods |
| 17 | b) It will return nil |
| 18 | a) def variable_name |
| 19 | b) By using @@ before the variable name |
| 20 | b) It is accessible across all instances of the class and subclasses |
| 21 | c) self |
| 22 | b) 5 |
| 23 | b) def self.method_name |
| 24 | a) By using @@variable_name |
| 25 | a) It allows a class to inherit methods from another class |
| 26 | a) class SubClass < SuperClass |
| 27 | a) super |
| 28 | b) It allows a method to act differently based on the object’s class |
| 29 | a) super() |
| 30 | a) A method that behaves differently based on the class of the object |