What Does Self Mean in Ruby

What does self mean in Ruby?

self refers to the object that is currently in context.

In your example, self is the class itself and def self.method is defining a class method. For example:

class MyClass
def self.method
puts "Hello!"
end
end

> MyClass.method
#=> "Hello"

You can also use self on instances of a class.

class MyClass
def method_a
puts "Hello!"
end

def method_b
self.method_a
end
end

> m = MyClass.new
> m.method_b
#=> "Hello!"

In this case, self refers to the instance of MyClass.

There is a good blog post on self in Ruby here, or, as it was pointed out in the comments, there is some more on this in the Ruby documentation.

What does `def self.function` name mean?

Contrary to other languages, Ruby has no class methods, but it has singleton methods attached to a particular object.

cat = String.new("cat")
def cat.speak
'miaow'
end
cat.speak #=> "miaow"
cat.singleton_methods #=> ["speak"]

def cat.speak creates a singleton method attached to the object cat.

When you write class A, it is equivalent to A = Class.new :

A = Class.new
def A.speak
"I'm class A"
end
A.speak #=> "I'm class A"
A.singleton_methods #=> ["speak"]

def A.speak creates a singleton method attached to the object A. We call it a class method of class A.

When you write

class A
def self.c_method
'in A#c_method'
end
end

you create an instance of Class(*). Inside the class definition, Ruby sets self to this new instance of Class, which has been assigned to the constant A. Thus def self.c_method is equivalent to def cat.speak, that is to say you define a singleton method attached to the object self, which is currently the class A.

Now the class A has two singleton methods, that we commonly call class methods.

A.singleton_methods
=> ["c_method", "speak"]

(*) technically, in this case where A has already been created by A = Class.new, class A reopens the existing class. That's why we have two singleton methods at the end. But in the usual case where it is the first definition of a class, it means Class.new.

what does class self mean in Rails?

That is the same as

class Post < ActiveRecord::Base

def self.search(q)
# Class Level Method
# search from DB
end

def search2(qq)
# Instance Level Method
# search from DB
end
end

Class methods work on the class (e.g. Post), instance methods works on instances of that class (e.g. Post.new)

Some people like the class << self; code; end; way because it keeps all class level methods in a nice block and in one place.

Others like to prefix each method with self. to explicitly know that is a class method not an instance method. It's a matter of style and how you code. If you put all class methods in a block like class << self, and this block is long enough, the class << self line might be out of your editor view making it difficult to know that you are in the class instance block.

On the other hand, prefixing each method with self. and intermixing those with instance methods is also a bad idea, how do you know all the class methods while reading your code.

Pick an idiom which you prefer for your own code base but if you work on an open source project or you collaborate on someone else's code, use their code formatting rule.

What does self do in ruby on rails?

This is a basic ruby question. In this case, self is used to define a class method.

    class MyClass
def instance_method
puts "instance method"
end

def self.class_method
puts "class method"
end
end

Which are used like this:

    instance = MyClass.new
instance.instance_method

Or:

    MyClass.class_method

Hope that clears things up a little bit. Also refer to: http://railstips.org/blog/archives/2009/05/11/class-and-instance-methods-in-ruby/

What does self. mean in a class method?

Using syntax def receiver.method you can define methods on a specific objects.

class Dog
def bark
puts 'woof'
end
end

normal_dog = Dog.new
angry_dog = Dog.new

def angry_dog.bite
puts "yum"
end

normal_dog.class # => Dog
angry_dog.class # => Dog

angry_dog.bite # >> yum
normal_dog.bite # ~> -:15:in `<main>': undefined method `bite' for #<Dog:0x007f9a93064cf0> (NoMethodError)

Note that even though dogs are of the same class Dog, one of them has a unique method that another dog doesn't.

The same thing with classes. Inside of class definition, self points to that class. This is critical to understanding.

class Foo
self # => Foo
end

Now let's look at these two classes:

class Foo
def self.hello
"hello from Foo"
end
end

class Bar
end

Foo.class # => Class
Bar.class # => Class

Foo.hello # => "hello from Foo"
Bar.hello # ~> -:15:in `<main>': undefined method `hello' for Bar:Class (NoMethodError)

Even though both Foo and Bar are both instances (objects) of class Class, one of has a method which another doesn't. The same thing.

If you omit the self in method definition, then it becomes instance method and it will be available on instances of a class rather than on the class itself. See the Dog#bark definition in the first snippet.

For closing, here's a couple more methods of how you can define a class instance method:

class Foo
def self.hello1
"hello1"
end

def Foo.hello2
"hello2"
end
end

def Foo.hello3
"hello3"
end

Foo.hello1 # => "hello1"
Foo.hello2 # => "hello2"
Foo.hello3 # => "hello3"

What is the 'self' keyword doing exactly in this Class method?

self is the class Restaurant. def self.method is how you implement a method on the class itself rather than an instance of the class. Restaurant.filter_by_city(...) rather than Restaurant.new.filter_by_city(...).

self changes in Ruby depending on context. Within a method, self is the object the method was called on.

Within the class Restaurant block, and outside of any method, self is the Restaurant object which is a Class object. Everything is an object in Ruby. Everything.

You can also do this by declaring a block where the class is the instance.

class << self
def filter_by_city(restaurants, city)
restaurants.select { |restaurant| restaurant.city == city }
end
end

Normally you'd use this syntax if you have a lot of class methods.

See Self in Ruby: A Comprehensive Overview for more.

class self idiom in Ruby

First, the class << foo syntax opens up foo's singleton class (eigenclass). This allows you to specialise the behaviour of methods called on that specific object.

a = 'foo'
class << a
def inspect
'"bar"'
end
end
a.inspect # => "bar"

a = 'foo' # new object, new singleton class
a.inspect # => "foo"

Now, to answer the question: class << self opens up self's singleton class, so that methods can be redefined for the current self object (which inside a class or module body is the class or module itself). Usually, this is used to define class/module ("static") methods:

class String
class << self
def value_of obj
obj.to_s
end
end
end

String.value_of 42 # => "42"

This can also be written as a shorthand:

class String
def self.value_of obj
obj.to_s
end
end

Or even shorter:

def String.value_of obj
obj.to_s
end

When inside a function definition, self refers to the object the function is being called with. In this case, class << self opens the singleton class for that object; one use of that is to implement a poor man's state machine:

class StateMachineExample
def process obj
process_hook obj
end

private
def process_state_1 obj
# ...
class << self
alias process_hook process_state_2
end
end

def process_state_2 obj
# ...
class << self
alias process_hook process_state_1
end
end

# Set up initial state
alias process_hook process_state_1
end

So, in the example above, each instance of StateMachineExample has process_hook aliased to process_state_1, but note how in the latter, it can redefine process_hook (for self only, not affecting other StateMachineExample instances) to process_state_2. So, each time a caller calls the process method (which calls the redefinable process_hook), the behaviour changes depending on what state it's in.



Related Topics



Leave a reply



Submit