Why use self. for a method?

hi all.
I had a problem with a methods and classes
what i had for example was this:

the controller:
class AnimalsController < ApplicationController
def index
@id =Animal.item
end
end

the model:
class Animal
def item
return 2
end
end

this doesn’t work because you have to maken from the Item Method a Class
Method.
you do this by doing def self.item.

But why ? and if you have mutiple methods in it you will have to set
them all to self. ??

jeljer

Heldop S. wrote:

hi all.
I had a problem with a methods and classes
what i had for example was this:

the controller:
class AnimalsController < ApplicationController
def index
@id =Animal.item
end
end

the model:
class Animal
def item
return 2
end
end

this doesn’t work because you have to maken from the Item Method a Class
Method.
you do this by doing def self.item.

But why ? and if you have mutiple methods in it you will have to set
them all to self. ??

jeljer

You are trying to call that method as a ‘class’ level method.

Adding self at the start declares a method as a class method, which is
why it then worked.

You probably want to be instantiating the object, so you would say

def index
animal = Animal.new;
@id = animal.item;
end

What is the difference between a “method” inside the class ModelName <
ActiveRecord::Base and a “class model” inside the same model* beside
having to use “self.” to make it work?

*the model is a class isn’t it?

On Mar 25, 11:03 pm, Dave F. [email protected]

Correction: I want to know the difference between a “method” and a
“class method” inside a model (which is a class, isn’t it?)

On 26 Mar 2008, at 06:19, Daniel D. wrote:

Correction: I want to know the difference between a “method” and a
“class method” inside a model (which is a class, isn’t it?)

When you have an instance method, you need an instance of the object.
For example if I have a Person class, and Person has a last_name
attribute it makes no sense to say Person.last_name, the class itself
doesn’t have a last name, only instances of Person do. If bob is an
instance of Person, then you can say bob.last_name and that makes
perfect sense.
With a class method you don’t need an instance of the class. For
example if Person is an ActiveRecord class then you have a class
method called find, so you can say Person.find (and writing bob.find
would be a bit weird).

The self. notation is because a class method is actually a singleton
method on the Class. All of your classes are instances of Class,
things like find and so on are singleton methods on those instances of
class. Equvalently you can write

class Foo
class << self
def a_class_method
end

def another_one
end

end
end

Fred

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs