Sonny Black
Sonny Black

Reputation: 1617

When is it appropriate to use class methods over instance methods?

So.....? When is it?

I've written a mini example below but it doesn't seem to work as "potato squash" isn't showing. It's returning: "you are eating a blank type of food"

class Food

        def initialize(food=“none”)
            @food = food
        end

        def self.food=(food=“none”)

        end

        def self.type?
            puts “you are eating a #{food} type of food” # defines the type of food you are eating.
        end
    end 

Food.new("potato squash")
Food.type?

Thx in advanced guys.

Upvotes: 2

Views: 112

Answers (3)

kddeisz
kddeisz

Reputation: 5182

None of your methods there should be class methods. Instance methods are used when you need to operate over data that is stored in an instance of a class. Class methods are used when you need to operate on data that pertains to that class.

For instance (no pun intended):

class Food
  def initialize(food="none")
    @food = food
  end

  # operating on data that is stored in this instance
  def type?
    puts "you are eating a #{@food} type of food"
  end

  # operating on data pertaining to this class
  def self.types
    return ['Fruits', 'Grains', 'Vegetables', 'Protein', 'Dairy']
  end
end 

Upvotes: 3

Benjamin Tan Wei Hao
Benjamin Tan Wei Hao

Reputation: 9691

    class Food
        attr_accessor :food
        def initialize(food="none")
            @food = food
        end

        def type?
            puts "you are eating a #{@food} type of food"
        end
    end

So how to choose between them?

I'll ask myself: @food, what is your type versus Food what is your type. See which ones makes more sense.

Just to deviate from your food example:

Instance methods apply to those questions you want to ask from a particular object. You don't ask a Person class for its name, but you do so for a @person object.

On the other hand, you ask a Person class, say, types_of_nationalities which may return you an array of all the nationalities. But you would ask a @person what his nationality is.

Hope this clears things up a little.

Upvotes: 1

jvperrin
jvperrin

Reputation: 3368

Try using this code instead, since type? is an instance method. Instance methods only work on an instance of the Food class (such as Food.new("potato squash")):

f = Food.new("potato squash")
f.type?

Upvotes: 0

Related Questions