Differencebetween Class and Klass in Ruby

Difference between a class and a module

The first answer is good and gives some structural answers, but another approach is to think about what you're doing. Modules are about providing methods that you can use across multiple classes - think about them as "libraries" (as you would see in a Rails app). Classes are about objects; modules are about functions.

For example, authentication and authorization systems are good examples of modules. Authentication systems work across multiple app-level classes (users are authenticated, sessions manage authentication, lots of other classes will act differently based on the auth state), so authentication systems act as shared APIs.

You might also use a module when you have shared methods across multiple apps (again, the library model is good here).

What is the difference between type of a class and superclass of a class in ruby?

Its a bit tricky. In Ruby everything is an Object (depending on your version).

  • Nil has its own NilClass, as it does not allow NilClass.new, which Object and Class allow. It is an object so you can call methods on it like nil.nil? etc.
  • Object is the highest Class, everything inherits from Object, even NilClass
  • Class is also an Object, it knows how to instantiate Objects from itself with the new method.

It is really weird at first, but I found the explanation from Dave Thomas quite revealing.

See: http://www.infoq.com/presentations/metaprogramming-ruby and http://pragprog.com/screencasts/v-dtrubyom/the-ruby-object-model-and-metaprogramming. The later is commercial.

What is the difference between Class and Klass in ruby?

class is a keyword used to define a new class. Since it's a reserved keyword, you're not able to use it as a variable name. You can't use any of Ruby's keywords as variable names, so you won't be able to have variables named def or module or if or end, etc - class is no different.

For example, consider the following:

def show_methods(class)
puts Object.const_get(class).methods.inspect
end
show_methods "Kernel"

Trying to run this results in an error, since you can't use class as a variable name.

test.rb:1: syntax error, unexpected kCLASS, expecting ')'
def show_methods(class)
^
test.rb:2: syntax error, unexpected ')'
puts Object.const_get(class).methods.inspect

To fix it, we'll use the identifier klass instead. It's not special, but it's conventionally used as a variable name when you're dealing with a class or class name. It's phonetically the same, but since it's not a reserved keyword, Ruby has no issues with it.

def show_methods(klass)
puts Object.const_get(klass).methods.inspect
end

show_methods "Kernel"

Output, as expected, is

["method", "inspect", "name", "public_class_method", "chop!"...

You could use any (non-reserved) variable name there, but the community has taken to using klass. It doesn't have any special magic - it just means "I wanted to use the name 'class' here, but I can't, since it's a reserved keyword".

On a side note, since you've typed it out wrong a few times, it's worth noting that in Ruby, case matters. Tokens that start with a capital letter are constants. Via the Pickaxe:

A constant name starts with an uppercase letter followed by name characters. Class names and module names are constants, and follow the constant naming conventions. By convention, constant variables are normally spelled using uppercase letters and underscores throughout.

Thus, the correct spelling is class and klass, rather than Class and Klass. The latter would be constants, and both Class and Klass are valid constant names, but I would recommend against using them for clarity purposes.

What are the practical differences between a module method and a class method in Ruby?

tl;dr: There are no class methods and module methods in Ruby, only instance methods. Considering that they are both just instance methods, and thus the same thing, there cannot possibly be any difference.


There is no such thing as a "class method" or a "module method" in Ruby. Ruby has exactly one kind of method: instance methods.

We sometimes use the word "class method" or "module method" out of convenience when talking about a certain pattern of using instance methods, but there is no such concept in Ruby. "Class methods" and "module methods" are really just singleton methods of an object which just happens to be an instance of the Module class or the Class class. There is absolutely no difference whatsoever between a singleton method of an object which happens to be an instance of Class, Module, String, Array, Hash, Object, Foo, Bar, Whatever, or Garbledigookidoo.

Oh. Did I mention? Singleton methods don't exist, either. Again, it is a word we use for certain kinds of usages of methods, but they are really just regular boring old instance methods of the singleton class of an object.

However, "instance method of the singleton class of foo" and "instance method of the singleton class of Foo, where Foo is an instance of Class" are really long, and so we shorten them to "singleton method of foo" and "class method of Foo" out of convenience, knowing full well that those are fictions that don't actually exist in the language.

Unlike Java, which has three different kinds of methods (instance methods, static methods, and constructors (which are kinda-sorta like methods)), Ruby has exactly one kind of method: instance methods. No class methods, no module methods, no global methods, no top-level methods, no static methods, no constructors. It does, however, have three kinds of classes: regular classes, singleton classes, and include classes (the latter being classes that get synthesized and injected into the inheritance hierarchy when you call include or prepend). These classes differ mainly in whether methods like Object#class, Class#superclass, and Class#ancestors display them or suppress them. Singleton classes are suppressed by all of them, include classes by the first two, but shown by ancestors.

What's the difference between a class and the singleton of that class in Ruby?

To answer your question directly: Module#define_method creates an instance method. A "class method" is an instance method on the singleton class (or eigenclass) of a Class object. I'm sure that sounds very confusing. Let me explain why Ruby includes the concept of "singleton classes" in the first place:

First, let me say that the basic "framework" of different object-oriented languages are quite varied. Ruby's design as regards objects, classes, metaclasses, etc. is by no means the only possible one, and the language could have been designed in a different way. Having said that, there are logical reasons why Ruby works the way it does. I'll try to explain as concisely as possible...

Think of a simple method call, like:

[1,2,3].first

Here we are calling a method called first, with an Array object as receiver. To process this method call, Ruby needs to search for a matching method definition, and execute it. Where does it start looking? Naturally, in the instance methods of Array. If it doesn't find it there, it will look in Array's superclass, then the superclass of the superclass, as well as Modules which are mixed into Array or its superclasses, etc.

"Class-based" (as opposed to prototype-based) object-oriented languages all work this way, more or less. If you've ever programmed in Java, or C++, or Python, this behavior should be familiar to you.

Now, the creator of Ruby wanted to also make it possible to add methods to just one object. In a prototype-based OO language, that would be easy, but how could it work in a class-based language? He made it possible by introducing the idea of "singleton classes" or "eigenclasses".

A "singleton class" is, simply, a class which has only one instance. I believe that rather than trying to keep track of a different singleton class for every single object, Ruby waits until the first time you try to access an object's singleton class, and then creates the class and inserts it into the object's inheritance chain dynamically.

As I just said, when a method is called, Ruby looks first in the object's class to find a matching definition, then the superclass, etc. Since singleton classes are inserted as the first link in an object's inheritance chain, they are the first place which Ruby will look for a method definition.

Bringing in the concept of "singleton classes" also solved another problem at the same time. In Java (for example), you can define static methods which are called on a class. In Ruby, people often want to do something similar. With "singleton" classes and methods, you can do just that: all you have to do is define a singleton method on a Class object.

(Remember that classes are also objects in Ruby. That's why the concept of "singleton" classes and methods can "kill 2 birds with 1 stone", as I explain above!)

EXTRA INFORMATION:

At the beginning, I mentioned "instance methods". I don't know if that might be confusing, or if you already know what "instance methods" are. When you define a Ruby class, like this...

class MyClass
def my_method
# do something
end
end

...then my_method will be added as an instance method of MyClass. When Ruby searches an object's class, superclass, etc. for a method definition, what it actually looks at are their instance methods. So an object's "methods" are the instance methods of its class, plus the instance methods of the superclass, the superclass of the superclass, etc.

About how singleton classes interact with method lookup in Ruby, there is a slight inconsistency which I didn't mention above. If you want to understand in detail:

Singleton classes of class objects are treated a little differently from singleton classes of other objects in general. If you have a class A which inherits from another class B, and B has singleton methods, A will inherit not just the instance methods, but also the singleton methods of B. In other words, B's singleton class is treated as a superclass of A's singleton class. This is not true of the singleton classes of any other objects.

difference between class method , instance method , instance variable , class variable?

First take a look at this diagram:

from "Metaprogramming Ruby" book

You can rightly say that “obj has a method called my_method( ),” meaning that you’re able to call obj.my_method(). By contrast, you shouldn’t say that “MyClass has a method named my_method().” That would be confusing, because it would imply that you’re able to call MyClass.my_method() as if it were a class method.

To remove the ambiguity, you should say that my_method() is an instance method (not just “a method”) of MyClass, meaning that it’s defined in MyClass, and you actually need an instance of MyClass to call it. It’s the same method, but when you talk about the class, you call it an instance method, and when you talk about the object, you simply call it a method. Remember this distinction, and you won’t get confused when writing introspective code like this:

String.instance_methods == "abc".methods # => true String.methods == "abc".methods # => false

an object’s instance variables live in the object itself, and an object’s methods live in the object’s class. That’s why objects of the same class share methods but don’t share instance variables.

Ruby class instance variable vs. class variable

Instance variable on a class:

class Parent
@things = []
def self.things
@things
end
def things
self.class.things
end
end

class Child < Parent
@things = []
end

Parent.things << :car
Child.things << :doll
mom = Parent.new
dad = Parent.new

p Parent.things #=> [:car]
p Child.things #=> [:doll]
p mom.things #=> [:car]
p dad.things #=> [:car]

Class variable:

class Parent
@@things = []
def self.things
@@things
end
def things
@@things
end
end

class Child < Parent
end

Parent.things << :car
Child.things << :doll

p Parent.things #=> [:car,:doll]
p Child.things #=> [:car,:doll]

mom = Parent.new
dad = Parent.new
son1 = Child.new
son2 = Child.new
daughter = Child.new

[ mom, dad, son1, son2, daughter ].each{ |person| p person.things }
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]

With an instance variable on a class (not on an instance of that class) you can store something common to that class without having sub-classes automatically also get them (and vice-versa). With class variables, you have the convenience of not having to write self.class from an instance object, and (when desirable) you also get automatic sharing throughout the class hierarchy.


Merging these together into a single example that also covers instance variables on instances:

class Parent
@@family_things = [] # Shared between class and subclasses
@shared_things = [] # Specific to this class

def self.family_things
@@family_things
end
def self.shared_things
@shared_things
end

attr_accessor :my_things
def initialize
@my_things = [] # Just for me
end
def family_things
self.class.family_things
end
def shared_things
self.class.shared_things
end
end

class Child < Parent
@shared_things = []
end

And then in action:

mama = Parent.new
papa = Parent.new
joey = Child.new
suzy = Child.new

Parent.family_things << :house
papa.family_things << :vacuum
mama.shared_things << :car
papa.shared_things << :blender
papa.my_things << :quadcopter
joey.my_things << :bike
suzy.my_things << :doll
joey.shared_things << :puzzle
suzy.shared_things << :blocks

p Parent.family_things #=> [:house, :vacuum]
p Child.family_things #=> [:house, :vacuum]
p papa.family_things #=> [:house, :vacuum]
p mama.family_things #=> [:house, :vacuum]
p joey.family_things #=> [:house, :vacuum]
p suzy.family_things #=> [:house, :vacuum]

p Parent.shared_things #=> [:car, :blender]
p papa.shared_things #=> [:car, :blender]
p mama.shared_things #=> [:car, :blender]
p Child.shared_things #=> [:puzzle, :blocks]
p joey.shared_things #=> [:puzzle, :blocks]
p suzy.shared_things #=> [:puzzle, :blocks]

p papa.my_things #=> [:quadcopter]
p mama.my_things #=> []
p joey.my_things #=> [:bike]
p suzy.my_things #=> [:doll]

Difference between class A; class B and class A::B

In Ruby, modules and classes are instances of the Module and Class classes, respectively. They derive their names from the constant they are assigned to. When you write:

class A::B
# ...
end

You are effectively writing:

A::B ||= Class.new do
# ...
end

Which is valid constant assignment syntax, and assumes that the A constant has been properly initialized and that it refers to a Module or a Class.

For example, consider how classes are usually defined:

class A
# ...
end

What is effectively happening is this:

Object::A ||= Class.new do
# ...
end

Now, when you write:

class A
class B
# ...
end
end

What actually happens looks like this:

(Object::A ||= Class.new).class_eval do
(A::B ||= Class.new).class_eval do
# ...
end
end

Here's what is happening, in order:

  1. A new Class instance is asssigned to the A constant of Object, unless it was already initialized.
  2. A new Class instance is asssigned to the B constant of A, unless it was already initialized.

This ensures the existence of all outer classes before attempting to define any inner classes.

There is also a change in scope, which allows you to directly access A's constants. Compare:

class A
MESSAGE = "I'm here!"
end

# Scope of Object
class A::B
# Scope of B
puts MESSAGE # NameError: uninitialized constant A::B::MESSAGE
end

# Scope of Object
class A
# Scope of A
class B
# Scope of B
puts MESSAGE # I'm here!
end
end

According to this blog post, the Ruby core team calls the "current class" the cref. Unfortunately, the author does not elaborate, but as he notes, it is separate from the context of self.


As explained here, the cref is a linked list that represents the nesting of modules at some point in time.

The current cref is used for constant and class variable lookup and
for def, undef and alias.


As the others have stated, they are different ways of expressing the same thing.

There is, however, a subtle difference. When you write class A::B, you assume that the A class has already been defined. If it has not, you will get a NameError and B will not be defined at all.

Writing properly nested modules:

class A
class B
end
end

Ensures the A class exists before attempting to define B.



Related Topics



Leave a reply



Submit