r/learnruby • u/jwjody • Sep 23 '14
Help understanding class methods
I'm reading Why's Poignant Guide to Ruby. In Chapter 3 he mentions class methods. And gives this example:
Door::new( :oak )
As seen above, the new class method is most often used to create things. In the above example, we’re asking Ruby to make a new oak door for us. Of course, Ruby has to have an understanding of how to make a door—as well as a wealth of timber, lumberjacks, and those long, wiggly, two-man saws.I don't understand what he means by class methods. Do you have to use the ':' symbol inside the () when using class methods?
Is this saying there's a class called Door that has a new method and we're passing it in 'oak'?
And we're creating this from a different class or file?
Is this the same thing as doing something like,
wood = "oak"
Door myDoor = new Door(wood)in Java?
1
Upvotes
View all comments
Show parent comment
1
u/zaclacgit Nov 13 '14
To piggyback on this, there are also class variables. They're variables particular to the class, but not instances of the class.
Continuing with the Door class example:
If you're building a house you probably need to have some doors. You'll have many types and styles of doors, like a front door, screen doors, bedroom doors. Let's say all of these are built using the Door::new class method. Let's also say that Door::new increments the Door class variable door_count.
Now every time you make a door a class variable is increased, and instances of the class don't have it. Why would your front door need to know how many doors are in the house? But you could have a Door.count that returns the number of doors because it's a class variable.