0
0
Rubyprogramming~5 mins

Extend for class methods in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the extend keyword do in Ruby?
It adds the methods from a module as class methods to the class or object it is called on.
Click to reveal answer
beginner
How is extend different from include in Ruby?
<code>include</code> adds module methods as instance methods, while <code>extend</code> adds them as class methods.
Click to reveal answer
beginner
Given <pre>module Greetings
  def hello
    "Hello!"
  end
end

class Person
  extend Greetings
end</pre> How do you call <code>hello</code>?
You call it on the class: Person.hello returns "Hello!".
Click to reveal answer
intermediate
Can extend be used on individual objects in Ruby?
Yes, it adds the module's methods as singleton methods to that object only.
Click to reveal answer
intermediate
Why use <code>extend</code> instead of defining class methods directly?
It promotes code reuse by sharing methods across classes without inheritance.
Click to reveal answer
What does extend add to a Ruby class?
ANothing, it just runs the module code
BInstance methods from a module
CConstants from a module
DClass methods from a module
Which keyword adds module methods as instance methods in Ruby?
Arequire
Bextend
Cinclude
Dimport
If a module has method foo, how do you call it after extend ModuleName in a class?
AClassName.foo
BClassName.new.foo
CModuleName.foo
DYou cannot call it
Can extend be used on a single object instance?
AYes, but adds methods to all instances
BYes, adds methods only to that object
CNo, only on classes
DNo, it raises an error
What is a main benefit of using extend for class methods?
AAvoids code duplication by sharing methods
BMakes code run faster
CChanges instance variables
DAutomatically creates instances
Explain how extend works to add class methods in Ruby.
Think about where the methods become available after using extend.
You got /3 concepts.
    Describe a scenario where using extend is better than inheritance.
    Consider when you want to share behavior but classes don’t share a parent.
    You got /3 concepts.