Official Ruby FAQ (2024)

If you wish to report errors or suggest improvements for this FAQ,please go to ourGitHub repositoryand open an issue or pull request.

Classes and modules

Can a class definition be repeated?

A class can be defined repeatedly. Each definition is added to the lastdefinition. If a method is redefined, the former one is overridden and lost.

Are there class variables?

There are. A variable prefixed with two at signs (@@) is a class variable,accessible within both instance and class methods of the class.

class Entity @@instances = 0 def initialize @@instances += 1 @number = @@instances end def who_am_i "I'm #{@number} of #{@@instances}" end def self.total @@instances endendentities = Array.new(9) { Entity.new }entities[6].who_am_i # => "I'm 7 of 9"Entity.total # => 9

However, you probably should use class instance variables instead.

What is a class instance variable?

Here the example of the previous section rewrittenusing a class instance variable:

class Entity @instances = 0 class << self attr_accessor :instances # provide class methods for reading/writing end def initialize self.class.instances += 1 @number = self.class.instances end def who_am_i "I'm #{@number} of #{self.class.instances}" end def self.total @instances endendentities = Array.new(9) { Entity.new }entities[6].who_am_i # => "I'm 7 of 9"Entity.instances # => 9Entity.total # => 9

Here, @instances is a class instance variable. It does not belongto an instance of class Entity, but to the class object Entity,which is an instance of class Class.

Class instance variables are directly accessible only within class methodsof the class.

What is the difference between class variables and class instance variables?

The main difference is the behavior concerning inheritance:class variables are shared between a class and all its subclasses,while class instance variables only belong to one specific class.

Class variables in some way can be seen as global variables withinthe context of an inheritance hierarchy, with all the problemsthat come with global variables.For instance, a class variable might (accidentally) be reassignedby any of its subclasses, affecting all other classes:

class Woof @@sound = "woof" def self.sound @@sound endendWoof.sound # => "woof"class LoudWoof < Woof @@sound = "WOOF"endLoudWoof.sound # => "WOOF"Woof.sound # => "WOOF" (!)

Or, an ancestor class might later be reopened and changed,with possibly surprising effects:

class Foo @@var = "foo" def self.var @@var endendFoo.var # => "foo" (as expected)class Object @@var = "object"endFoo.var # => "object" (!)

So, unless you exactly know what you are doing and explicitly needthis kind of behavior, you better should use class instance variables.

Does Ruby have class methods?

A singleton method of a class object is called aclass method.(Actually, the class method is defined in the metaclass, but that is prettymuch transparent). Another way of looking at it is to say that a class methodis a method whose receiver is a class.

It all comes down to the fact that you can call class methods without havingto have instances of that class (objects) as the receiver.

Let’s create a singleton method of class Foo:

class Foo def self.test "this is foo" endend# It is invoked this way.Foo.test # => "this is foo"

In this example, Foo.test is a class method.

Instance methods which are defined in class Class can be usedas class methods for every(!) class.

What is a singleton class?

A singleton class is an anonymous class that is created by subclassing theclass associated with a particular object. Singleton classes are anotherway of extending the functionality associated with just one object.

Take the lowly Foo:

class Foo def hello "hello" endendfoo = Foo.newfoo.hello # => "hello"

Now let’s say we need to add class-level functionality to just this oneinstance:

class << foo attr_accessor :name def hello "hello, I'm #{name}" endendfoo.name = "Tom"foo.hello # => "hello, I'm Tom"Foo.new.hello # => "hello"

We’ve customized foo without changing the characteristics of Foo.

What is a module function?

This section or parts of it might be out-dated or in need of confirmation.

A module function is a private, singleton method defined in a module.In effect, it is similar to a class method,in that it can be called using the Module.method notation:

Math.sqrt(2) # => 1.414213562

However, because modules can be mixed in to classes, module functions canalso be used without the prefix (that’s how all those Kernel functions aremade available to objects):

include Mathsqrt(2) # => 1.414213562

Use module_function to make a method a module function.

module Test def thing # ... end module_function :thingend

What is the difference between a class and a module?

Modules are collections of methods and constants. They cannot generateinstances. Classes may generate instances (objects), and have per-instancestate (instance variables).

Modules may be mixed in to classes and other modules. The mixed in module’sconstants and methods blend into that class’s own, augmenting the class’sfunctionality. Classes, however, cannot be mixed in to anything.

A class may inherit from another class, but not from a module.

A module may not inherit from anything.

Can you subclass modules?

No. However, a module may be included in a class or another module to mimicmultiple inheritance (the mixin facility).

This does not generate a subclass (which would require inheritance), but doesgenerate an is_a? relationship between the class and the module.

Give me an example of a mixin

The module Comparable provides a variety of comparison operators(<, <=, ==, >=, >, between?). It defines these in termsof calls to the general comparison method, <=>. However, it doesnot itself define <=>.

Say you want to create a class where comparisons are based on the number oflegs an animal has:

class Animal include Comparable attr_reader :legs def initialize(name, legs) @name, @legs = name, legs end def <=>(other) legs <=> other.legs end def inspect @name endendc = Animal.new("cat", 4)s = Animal.new("snake", 0)p = Animal.new("parrot", 2)c < s # => falses < c # => truep >= s # => truep.between?(s, c) # => true[p, s, c].sort # => [snake, parrot, cat]

All Animal must do is define its own semantics for the operator <=>,and mix in the Comparable module. Comparable’s methods now becomeindistinguishable from Animal’s and your class suddenly sprouts newfunctionality. And because the same Comparable module is used by manyclasses, your new class will share a consistent and well understood semantics.

Why are there two ways of defining class methods?

You can define a class method in the class definition, and you can definea class method at the top level.

class Demo def self.class_method endenddef Demo.another_class_methodend

There is only one significant difference between the two.In the class definition you can refer to the class’s constants directly,as the constants are within scope. At the top level, you have to use theClass::CONST notation.

What is the difference between include and extend?

This section or parts of it might be out-dated or in need of confirmation.

include mixes a module into a class or another module. Methods from thatmodule are called function-style (without a receiver).

extend is used to include a module in an object (instance).Methods in the module become methods in the object.

What does self mean?

self is the currently executing receiver, the object to which a methodis applied. A function-style method call implies self as the receiver.

Official Ruby FAQ (2024)
Top Articles
Neodymium Magnets in Aquariums and Saltwater
Best High Frequency (HFT) Brokers of 2024
Golden Abyss - Chapter 5 - Lunar_Angel
Sprinter Tyrone's Unblocked Games
Erika Kullberg Wikipedia
Overnight Cleaner Jobs
Davante Adams Wikipedia
Aiken County government, school officials promote penny tax in North Augusta
Urinevlekken verwijderen: De meest effectieve methoden - Puurlv
Raid Guides - Hardstuck
O'reilly's Auto Parts Closest To My Location
TS-Optics ToupTek Color Astro Camera 2600CP Sony IMX571 Sensor D=28.3 mm-TS2600CP
Clarksburg Wv Craigslist Personals
Connect U Of M Dearborn
Katherine Croan Ewald
Best Uf Sororities
Healthier Homes | Coronavirus Protocol | Stanley Steemer - Stanley Steemer | The Steem Team
Teacup Yorkie For Sale Up To $400 In South Carolina
Bernie Platt, former Cherry Hill mayor and funeral home magnate, has died at 90
Barber Gym Quantico Hours
Wbiw Weather Watchers
Ford F-350 Models Trim Levels and Packages
Xfinity Outage Map Fredericksburg Va
Best Sports Bars In Schaumburg Il
Boise Craigslist Cars And Trucks - By Owner
Lexus Credit Card Login
Times Narcos Lied To You About What Really Happened - Grunge
4.231 Rounded To The Nearest Hundred
Florence Y'alls Standings
Used 2 Seater Go Karts
Gasbuddy Lenoir Nc
The Pretty Kitty Tanglewood
Junee Warehouse | Imamother
Cvb Location Code Lookup
Edict Of Force Poe
Are you ready for some football? Zag Alum Justin Lange Forges Career in NFL
Instafeet Login
Gets Less Antsy Crossword Clue
Tokyo Spa Memphis Reviews
Craigslist Gigs Wichita Ks
Felix Mallard Lpsg
11301 Lakeline Blvd Parkline Plaza Ctr Ste 150
Entry of the Globbots - 20th Century Electro​-​Synthesis, Avant Garde & Experimental Music 02;31,​07 - Volume II, by Various
Cpmc Mission Bernal Campus & Orthopedic Institute Photos
Pain Out Maxx Kratom
Hk Jockey Club Result
Avatar: The Way Of Water Showtimes Near Jasper 8 Theatres
Okta Login Nordstrom
Barber Gym Quantico Hours
Fallout 76 Fox Locations
Craigslist Cars And Trucks For Sale By Owner Indianapolis
Latest Posts
Article information

Author: Rubie Ullrich

Last Updated:

Views: 6404

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Rubie Ullrich

Birthday: 1998-02-02

Address: 743 Stoltenberg Center, Genovevaville, NJ 59925-3119

Phone: +2202978377583

Job: Administration Engineer

Hobby: Surfing, Sailing, Listening to music, Web surfing, Kitesurfing, Geocaching, Backpacking

Introduction: My name is Rubie Ullrich, I am a enthusiastic, perfect, tender, vivacious, talented, famous, delightful person who loves writing and wants to share my knowledge and understanding with you.