Class instance method

Consider this irb session

C:\InstantRails-2.0-win\rails_apps>irb
irb(main):001:0> class M
irb(main):002:1> @w = “ralph”
irb(main):003:1>
irb(main):004:1* def M.v
irb(main):005:2> @w
irb(main):006:2> end
irb(main):007:1>
irb(main):008:1* end
=> nil
irb(main):009:0>
irb(main):010:0* puts M.v
ralph
=> nil
irb(main):011:0> puts M::v
ralph
=> nil

I think I understand M.v but what does M::v mean? Is there a semantic
and/or philosophical difference between the two?

In the case of a method they’re approximately the same:

==== begin snippet ====
module M
def self.foo; “foo”; end
end

M.foo

=> “foo”

M::foo

=> “foo”

==== end snippet ====

But sometimes you want to access constants, not methods. Then
they’re drastically different:

==== begin snippet ====
module M
module Inner; end
end

M::Inner

=> M::Inner

M.Inner

=> NoMethodError: undefined method `Inner’ for M:Module

==== end snippet ====

John F.
Principal Consultant, BitsBuilder
LI: http://www.linkedin.com/in/johnxf
SO: http://stackoverflow.com/users/75170/

v() is called a ‘class method’, or a ‘singleton method’ of M–not a
‘class instance method’.

I didn’t know you could use the :: syntax to call the method, but M::v
basically means go into M and execute v. You will typically see that
syntax used in these situations:

module Animals

class Dog
def speak
puts “bow wow”
end
end

end

dog = Animals::Dog.new
dog.speak

Also, when I said that they were “approximately” the same, there are a
few exceptions, though you should rarely if ever encounter them if you
stick to Ruby’s conventions. One example of a difference between
“M::(…)” and “M.(…)”:

==== begin snippet ====
module M
def self.Foo; “foo”; end
module Foo; end
end

M::Foo

=> M::Foo

M.Foo

=> “foo”

==== end snippet ====

The reason you should never encounter this is because it’s considered
a violation of the conventions if you don’t start methods with a
lowercase letter. That’s why we can safely stick to “M::(…)” for
referencing namespaces created by methods or classes, and “M.(…)”
for invoking methods.

John F.
Principal Consultant, BitsBuilder
LI: http://www.linkedin.com/in/johnxf
SO: http://stackoverflow.com/users/75170/

Ralph S. wrote in post #1003180:

I think I understand M.v but what does M::v mean?

Formally, the :: is known as the ‘scope resolution operator’.

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