I am writing a class in Ruby where I have instance variables (i.e. @person_summary_info, @name, @dob, @favorite_food) for the class.
To parse a piece of text, I have a public method that I call from outside the class (let’s call it interpret).
This method calls some private class methods such as get_name that use @person_summary_info to extract the respective piece of information (in this case, the name of the person). Should those private methods:
a) use the instance @person_summary_info, or get that information through a parameter passed to them (i.e. get_name vs get_name(person_summary_info))
b) modify the instance variable directly and return nothing, or modify nothing outside the scope of the function, and return the result (i.e. inside get_name, set @name = 'John', or return 'John')?
What is the best practice here?
Thanks!
I have included my best representation of your question in code at the bottom of my answer, but I’d like to present my solution as I understand your dilemma first…
Do this if your
nameattribute is meant to be publicly accessible:Do this if your
nameattribute should not be (easily) publicly accessible: (For what it’s worth, pretty much anything can be accessed one way or another in Ruby. One of the many things that make it awesome!)And, as mentioned above, here’s my best translation of your question into code:
Hopefully, you can see why there’s some confusion in the comments about what you are asking exactly. If nothing else, maybe seeing this will help you to form your question more clearly so we can help!
Finally, you should avoid writing your own getters/setters in Ruby unless you need to hook in some custom code to the getting/setting processes — use the class-level
attr_reader/attr_writer/attr_accessormacros to create them for you.