Class, Instance and Singleton methods

There are three types of methods in Ruby and I always get them confused. Here, for my future reference, is what I currently think they mean.

Class methods

Methods which can be called directly on a class.

Time.now
Monkey.find(:all)

Instance methods

Methods which can be called on any instance of that class.

@widget.to_s
Time.now.to_f

Singleton methods

Methods which can be called only on a specific instance of that class.

chicken = Chicken.new
class << chicken
  def hide
    # ...
  end
end
chicken.hide

About the boy

A picture of Craig in grayscale

Craig Webster is a software engineer living in London. He usually works with Ruby although sometimes he sneaks in some Erlang or JavaScript. He's into rock climbing, snowboarding, skating, photography and fencing. Yes, this does mean he has a sword.

Near here you'll find Craig's homepage, contact details, PGP key and keysigning policy, and talks.

Licence

The entire content of this blog is public domain. Use it however you fancy. You don't even need to attribute it to me, although it would be nice if you did. Just don't sue me and we'll all be happy.

I Work With Rails

Recommend Me

My Travels

I go places. Do you go places too? Let's meet up!.