programmer321 programmer321 - 2 months ago 12
Ruby Question

In the latest version of Ruby, is having both getter and setter methods necessary to access instance variables?

I am learning from a tutorial on an educational website. The problem is that the video is from 2009 (Ruby 1.8), and some of the information may be outdated.

The instructor says that you need to use both getter/setter methods to access instance variables but a simple test shows otherwise:

class Carnivore
def noise(noise)
@noise = noise

carnivore =
puts noise = "roar" #will output "roar"

I am unsure to whether I have done something wrong in my setter method that it's letting me access the instance variable, when it ideally shouldn't. What's confusing me is that my instructor showed me a program breaking without having both a getter and setter method.

In my mind, the above situation works due to a) my setter method being improperly set, or b) a version change in Ruby that allows for a setter to be set, and then accessed without a getter.

So I guess my question is that do you need both getter AND setter methods to access instance variables?

puts noise = "roar" 

This line has nothing to do with the previous lines - not with the class Carnivore, not with the instance carnivore. It creates a local variable noise (and prints it). Start experimenting with

puts carnivore.noise