Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby Ruby Foundations Methods Class Methods

SERGIO RODRIGUEZ
SERGIO RODRIGUEZ
17,532 Points

Why are class methods useful? Are they good practice?

I took the whole Learn Ruby track and class methods where not mentioned anywhere.

I find this class methods strange, why are they useful? Are they good practice?

1 Answer

Jessica H
Jessica H
16,612 Points

Here's a spec for a local method :

 describe '#description' do
    it 'describes what task is being done' do
      test_task = Task.new("wash the dishes")
      test_task2 = Task.new("feed the dog")
      expect(test_task.description).to eq "wash the dishes"
    end
end

I am calling the description method on a string so that I can get just this string back, or some other strings that I put inside it. I called for test_task back instead of test task 2.

CLASS method

 describe '.all' do
   it 'empty at first' do
     expect(Task.all).to eq []
   end
end

I am calling the all method on the entire class, so that I can get a list (array) back of all the tasks that I added to the array. Right now it is empty, so I have to add a "local" save method below.

 describe '#save' do
    it 'adds task and saves to the list' do
      test_task = Task.new("go to the grocer")
      test_task2 = Task.new("cook dinner for kids")
      test_task.save
      test_task2.save
      expect(Task.all).to eq [test_task, test_task2]
    end
end

So now that class method gave me back all the things I added within it instead of one thing like "description." The class method would be able to take everything within itself and do something.

When you want the class method to have access to everything within it, then it makes sense. It just depends on what the method is. In general, it wont be doing too much work. What if "save" was a class method? Somehow I think it would just change and overwrite everything to whatever you put in, rather than add multiple things to the list

Other methods to keep in mind are .clear and .find.

The find or search method would look through all of the things you add in your program and give back a specific one.

I don't know if this helps. Sorry :)