Method call within a class

L

Li Chen

Hi all,

Maybe I miss something. But I am confused about method call within a
class. What is the format for that? I just copy some code segments from
the forum as follows:

module Enumerable
def each_with_index
i = 0
each do |elem|
yield elem, i
i += 1
end
end
end

class Array
def each_with_index
size.times do |i|
yield self, i
end
end
end

So
1) which one is the reciever for "each"?
2) which one is the reciever for "size"?

Do they default to self?

Thanks,

Li
 
A

Andrea Dallera

Hei,

"each"'s receiver will be an instance of a class that includes the
module Enumerable and "size"'s receiver will be an instance of the class
Array. Example:

array = Array.new
p array.size # => 0

class MyEnumerable
include Enumerable

end

foo = MyEnumerable.new
foo.each_with_index # doesn't raise, the method is defined

HTH
 
L

Li Chen

Andrea said:
Hei,

"each"'s receiver will be an instance of a class that includes the
module Enumerable and "size"'s receiver will be an instance of the class
Array. Example:

array = Array.new
p array.size # => 0

class MyEnumerable
include Enumerable

end

foo = MyEnumerable.new
foo.each_with_index # doesn't raise, the method is defined

Hi Andrea,

Thank you very much. So the receiver can be omitted when the method is
called within a class, right?

Li
 
A

Andrea Dallera

Hei Li,

yes, the default deceiver is 'self' so, if omitted, the receiver for
any message will be the istance itself.
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

Hi Andrea,

Thank you very much. So the receiver can be omitted when the method is
called within a class, right?

Li
Except on assignments, because it looks like you are creating a local
variable.
Example:

class Foo
attr_accessor :bar
def bad_assign
bar = 'baz'
defined? bar
end
def good_assign
self.bar = 'baz'
defined? bar
end
end

foo = Foo.new

foo.bad_assign # => "local-variable"
foo.bar # => nil

foo.good_assign # => "method"
foo.bar # => "baz"
 
L

Li Chen

Josh said:
Except on assignments, because it looks like you are creating a local
variable.
Example:

class Foo
attr_accessor :bar
def bad_assign
bar = 'baz'
defined? bar
end
def good_assign
self.bar = 'baz'
defined? bar
end
end

foo = Foo.new

foo.bad_assign # => "local-variable"
foo.bar # => nil

foo.good_assign # => "method"
foo.bar # => "baz"


Thank you so much. Where can I find more info about this usage?

Li
 

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,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top