What's the difference in calling method vs self.method?

J

Jim

Here's some example code. In method_b, what is the difference in
calling method_a and self.method_a?


class HoHo

def method_a
puts "Hello, HoHo"
end

def method_b
method_a
self.method_a
end

end

hoho = HoHo.new
hoho.method_b
 
J

Joseph Divelbiss

Jim said:
Here's some example code. In method_b, what is the difference in
calling method_a and self.method_a?

I am sure that the more experienced coders will speak up soon, but until
then Ill do my best.

The self. is implied when you call the method..
just as self.puts or self.gets are often written puts or gets
respectively..

Hope that makes sense.
 
J

Jim

Jim said:
Here's some example code. In method_b, what is the difference in
calling method_a and self.method_a?

I just had a thought that it may very well make a difference in the
case of a conflict method names. For example if you had (puposely or
not) created 2 method_a's in the same scope. Make sense?
 
M

Marcin Mielżyński

Jim said:
Here's some example code. In method_b, what is the difference in
calling method_a and self.method_a?

In Your code it makes no difference, however there are situations when
You'll have to explicitly resolve method invocation, consider:

class C
def meth1
end

def meth2
meth1 # no problem, but..
meth1=4 # variable assignment
self.meth1 # so we have to resolve it as a method
end
end

other thing is operator method invocation:

class D

def + arg
p arg
end

def meth
+ 2 # Ruby sees it as unary plus, aka +@
self + 2 # explicit
end

end


lopex
 
R

Ross Bamford

In Your code it makes no difference, however there are situations when
You'll have to explicitly resolve method invocation, consider:

class C
def meth1
end

def meth2
meth1 # no problem, but..
meth1=4 # variable assignment
self.meth1 # so we have to resolve it as a method
end
end

other thing is operator method invocation:

class D

def + arg
p arg
end

def meth
+ 2 # Ruby sees it as unary plus, aka +@
self + 2 # explicit
end

end

Somewhat related to the above is the following case:

class Clz
attr_accessor :myattr

def amethod
# doesn't work, Ruby treats as local assignment
# myattr = 5

# We have to be explicit.
self.myattr = 5
end
end

Another area I guess it could make a difference is:

class ClzToo

def amethod
# doesn't work, private methods cannot be called
# with a receiver.
# puts self.aprivate

# So we can only call without 'self'
puts aprivate
end

private

def aprivate
"private"
end
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top