What is a class in Ruby?
A class is a blueprint for creating objects. It defines the data and behaviors (methods) that its objects will have.
How do you define a class in Ruby?
Use the ‘class’ keyword followed by the class name (CamelCase)
What is an object in Ruby?
An object is an instance of a class. Almost everything in Ruby is an object
How do you create an object from a class?
Call .new on the class: dog = Dog.new
What is the initialize method used for?
It’s a constructor method that runs automatically when you create a new object. It usually sets up instance variables.
How do you define an instance variable?
Start with ‘@’ inside a class. Example: @name = "Nick"
What is the difference between an instance variable and a class variable?
An instance variable (@var) belongs to one object. A class variable (@@var) is shared among all instances of a class.
What is a module in Ruby?
A module is a collection of methods and constants. It cannot be instantiated but can be included or extended into classes.
How do you include a module into a class?
Use include ModuleName to add module methods as instance methods.
How do you extend a module into a class?
Use extend ModuleName to add module methods as class methods.
What is ‘Enumerable’ in Ruby?
A module that adds powerful iteration methods like map
Which Ruby class includes the Enumerable module by default?
The Array and Hash classes (and any class that defines an each method).
What does the ‘map’ method do?
It transforms each element in a collection based on a block and returns a new array of results.
What does the ‘select’ method do?
It filters elements from a collection based on a condition in the block and returns those that evaluate to true.
What does the ‘reduce’ (or ‘inject’) method do?
It accumulates a result across elements in a collection
What is the difference between ‘each’ and ‘map’?
each iterates and returns the original array; map returns a new array with transformed elements.
What is a block in Ruby?
A block is a chunk of code enclosed in {} or do...end that can be passed to methods for execution.
How do you yield to a block inside a method?
Use the yield keyword to call the block passed to a method.
What happens if you call yield without a block being given?
It raises a LocalJumpError unless you check with block_given? first.
What are Procs in Ruby?
A Proc (procedure) is an object that encapsulates a block of code
How do you create a Proc?
Use Proc.new { ... } or proc { ... }.
How do you call a Proc?
Use .call on it
What is a lambda in Ruby?
A lambda is similar to a Proc but checks arguments strictly and returns control differently.
How do you create a lambda?
Use lambda { ... } or the shorthand -> { ... }.