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


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

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}"

janedoe ="Jane", 50)

or is it alternatively better to do the following?

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


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

janedoe ="Jane Doe", 50)


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:


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