«

»

Sep 12

Class is Class, and Instance, Instance, and never the twain shall meet

More about methods, it’s inspired/spurred by a comment on methods, public_methods, and private_methods by Pit Captain. It also corrects some misconceptions I had (and may have (wrongly) given others).

I’ve added a new category, “eating crow” for this and any other postings where I step back and re-evaluate my posts. This is to keep me honest, and, if y’all would, please feel free to tell me when it’s time to “eat crow”.

I’d gotten a little confused. Seeing #initialize as a private method of Object (the class) I made the (wrong) assumption that an instance was inheriting it. Here’s what led to my downfall:

However, these methods are not the same:

We can see that the class method Foo#bar is not accessible within the instance — it would need to be explicitly called.

Also, below you can see that both the class and the instance can have, due to the magick of scope, the same method:

As an aside, #initialize is by definition a private method:

initialize is a special method in Ruby programs. When you call Song.new to create a new Song object, Ruby creates an uninitialized object and then calls that object’s initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object’s state. — http://www.rubycentral.com/book/tut_classes.html

1 comment

1 ping

  1. Eric

    You say: We can see that the class method Foo#bar is not accessible within the instance — it would need to be explicitly called.

    In Ruby notation, Class#method is typically used to indicate an instance method and Class::method to indicate a class method.

    Also, classes and instances *do* actually meet in Ruby. A class is actually an instance of a class named Class.

    irb(main):001:0> class Foo
    irb(main):002:1> end
    => nil
    irb(main):003:0> f = Foo.new
    => #
    irb(main):004:0> f.class
    => Foo
    irb(main):005:0> Foo.class
    => Class

  1. Ramblings » Blog Archive » methods, public_methods, and private_methods

    […] it’s not a public method of the instance, but rather a private method of the class(Note: see Class is Class and Instance, Instance, and never the twain shall meet for why the edit is here): irb(main):013:0> MethodsTest.private_methods.include? […]

Leave a Reply

%d bloggers like this: