0

Here is a quote from Trying to learn / understand Ruby setter and getter methods:

What's happening in your example is that you're initializing a new object (Human.new), and then using a method (noise=, yes the method name contains the = symbol) that just-so-happens to define an instance variable (that is, a variable just for that instance), and then finally retrieving that instance variable with another method call.

Question: why is it necessary to retrieve an instance variable with another method call? I read somewhere about in Ruby having all instance variables private. Does this mean that when focus passes to another instance/object, the instance variable is destroyed and/or inaccessible and thus requires a method call?

Community
  • 1
  • 1
Drew Rush
  • 710
  • 5
  • 19

3 Answers3

1

It isn't really. When setting something, the new value is returned. Eg:

foo = 'bar' #=> "bar"

Also:

class Foo
  def bar=(obj)
    @bar = obj
  end
  def bar
    @bar
  end
end

f = Foo.new
f.bar = "FOO" # returns "FOO"
f.bar         # Now also returns "FOO"

The purpose of using another method is simply when you want to access the variable later.

Shelvacu
  • 4,245
  • 25
  • 44
0

Private instance variables are inaccessible from outside of their instance.

That's often useful because it allows your classes to keep track of internal state which should not be visible to other objects. However in cases where you would like to allow other object to retrieve a value from instances of your class you can provide a getter method to expose that value.

The object(s) accessing values from getters are often different from the objects which set those values in the first place. For example we could represent this question as an object. Drew set the question's text. Now this question is not very useful unless the rest of us have some way to also get the question's text so that we can read it. Without a getter we are very unlikely to be able to create useful answer objects. Even Drew might want to use that getter since Andrew came along and edited the question and Drew might want to know what the next text looks like.

Jonah
  • 17,918
  • 1
  • 43
  • 70
0

You can choose to expose instance variables if you wish, ruby provides the following syntax:

class Foo
  attr_reader :bar

  def initialize(bar)
    @bar = bar
  end
end

foo_instance = Foo.new('some_value')
puts foo_instance.bar # => 'some_value'

You will see attr_reader under the class Foo line, that makes whatever value @bar is retrievable.

You can also make the instance variable open for modification:

  class Foo
    attr_accessor :bar

    def initialize(bar)
      @bar = bar
    end
  end

 foo_instance = Foo.new('some_value')
 puts foo_instance.bar # => 'some_value'
 foo_instance.bar = 'another_value'
 puts foo_instance.bar # => 'another_value'

This is accomplished using the attr_accessor lets you see @bar contents and change it.

Discorick
  • 1,546
  • 2
  • 10
  • 15