tags:

views:

451

answers:

3

Hi, I was reading a Ruby book and came across this definition of the pseudo-variable self:

self - receiver object of the current method

Could someone break down that definition and explain what it means? I don't understand any of it.

EDIT: I actually have a pretty good idea of what self is (and its applications) and I know how to search on Google. I was just wondering if someone could explain the definition I quoted. That specifically.

+6  A: 

self is a special variable that changes depending on the context. To be more specific, it is receiver object of the current method, as you mentioned. To understand this, we need to understand what receiver means.

See Programming Ruby: More About Methods and Classes and Objects.

You call a method by specifying a receiver, the name of the method, and optionally some parameters and an associated block.

connection.downloadMP3("jitterbug") { |p| showProgress(p) }

In this example, the object connection is the receiver, downloadMP3 is the name of the method, "jitterbug" is the parameter, and the stuff between the braces is the associated block.

foo = "hello"
bar = foo.dup
class <<foo
  def to_s
    "The value is '#{self}'"
  end
  def twoTimes
    self + self
  end
end

foo.to_s        » "The value is 'hello'"
foo.twoTimes    » "hellohello"
bar.to_s        » "hello"

In foo.twoTimes, foo part is called the receiver of the method call. So, within the twoTimes method, self refers to the object foo in the context.

eed3si9n
+5  A: 
jmah
+2  A: 

self - receiver object of the current method

"Method calling" in Ruby is accomplished through a message-sending mechanism. So

some_object.some_method(args)

is a shorthand for

some_object.send(:some_method, args)

I think this is what the quote is referring to: "self" is the object to which the message (or method) has been sent: the receiver of the current method.

The whole message-sending thing is part of what makes Ruby so dynamic. It makes it easy for an object to define method_missing for messages it doesn't currently handle and decide what to do with them. Rails uses this a lot: ActiveRecord, for example has the "find_by..." syntax, which figures out what's wanted from the name of the method called/sent.

Mike Woodhouse