Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby current class

Tags:

ruby

How do I determine the current open class in Ruby?

like image 862
Chandra Patni Avatar asked Nov 20 '10 00:11

Chandra Patni


People also ask

What is class New Ruby?

Classes in Ruby are first-class objects—each is an instance of class Class . Typically, you create a new class by using: class Name # some code describing the class behavior end. When a new class is created, an object of type Class is initialized and assigned to a global constant ( Name in this case).

What is a Ruby class?

What is a class in Ruby? Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects. Objects are the products of the class.

What is :: in Ruby?

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module. Remember in Ruby, classes and methods may be considered constants too.


3 Answers

Inside of a class definition body, self refers to the class itself. Module#name will tell you the name of the class/module, but only if it actually has one. (In Ruby, there is no such thing as a "class name". Classes are simply objects just like any other which get assigned to variables just like any other. It's just that if you happen to assign a class object to a constant, then the name method will return the name of that constant.)

Example:

puts class Foo
  name
end
# Foo

But:

bar = Class.new
bar.name # => nil
BAR = bar
bar.name #=> 'BAR'
like image 137
Jörg W Mittag Avatar answered Oct 06 '22 13:10

Jörg W Mittag


Inside the class itself:

class_name = self.class

On an initialized object named obj:

class_name = obj.class
like image 22
Alex Avatar answered Oct 06 '22 12:10

Alex


if you have obj = SomeClass.new you get the class with obj.class

like image 25
cristian Avatar answered Oct 06 '22 12:10

cristian