Class instance method

Discussion in 'Ruby' started by Ralph Shnelvar, Jun 5, 2011.

  1. 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?
     
    Ralph Shnelvar, Jun 5, 2011
    #1
    1. Advertisements

  2. 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 Feminella, Jun 5, 2011
    #2
    1. Advertisements

  3. 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.(...)":

    =3D=3D=3D=3D begin snippet =3D=3D=3D=3D
    module M
    def self.Foo; "foo"; end
    module Foo; end
    end

    M::Foo
    # =3D> M::Foo

    M.Foo
    # =3D> "foo"
    =3D=3D=3D=3D end snippet =3D=3D=3D=3D

    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 Feminella, Jun 5, 2011
    #3
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.