How to decide when a method should be defined in a class or outside?


#1

Hi all,
I understand that class methods are written inside of the body of a class, but I'm still a bit unsure on when to define a method inside or outside of the class.

Is this purely dependent on the input variables into a method? Is there generally a preferred style? Below is a rough example of what I mean:

def Person
attr accessor :name, :age

def initialize (name, age)
@name = name
@age = age
end

and then after this, is it better to do this the following way:

def greet
puts "Hi, my name is #{@name} and my age is #{@age}"
end
end

janedoe = Person.new("Jane", 50)
janedoe.greet

or is it alternatively better to do the following?

or is it better to close up the class and make the greeting outside?

end

def greet(person1)
puts "Hi, my name is #{person1.name} and my age is #{person1.age}"
end

janedoe = Person.new("Jane Doe", 50)
greet(janedoe)


#2

Nice question! :slight_smile:

I would recommend the first method. It clearly shows that greet is a method associated exclusively only with objects of the Person class. Also, it secures the name greet inside of a class. So, you can have a global variable named greet and Ruby wouldn't confuse that global variable when you call person.greet.

The second method not only exposes a global variable, it also doesn't make it clear as to what type of objects it can be called with. Of course, you can write comments there explaining its use but that's really not the best way.

I hope I was able to explain it properly :slight_smile:


#3

Thanks for the reply! this is very helpful!! :smile: