0

I am learning Ruby OOP and have been faced with the following question.

What could we add to the class below to access the instance variable @volume?

class Cube
  def initialize(volume)
    @volume = volume
  end
end

My initial thought was to add attr_reader :volume to access the instance variable.

Instead the model answer suggests adding a new method as below.

def get_volume
  @volume
end

Why is this the preferred method? Both methods would output 100 if cube.volume or cube.get_volume were called.

1
  • 3
    The resource you're learning this from is crap. Commented Sep 5, 2015 at 10:37

4 Answers 4

5

attr_reader. In general methods with get_ prefix are rather avoided in Ruby community (in opposite to commonly seen in Java/C# code)

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, exactly as you thought.
0

If it is a dynamically created variable, then you can use instance_vairable_get, like below -

instance_variable_get("@volume") 

Comments

0

Since it is desired to get the variable volume ,I will suggest the use of attr_reader :volume. This creates a proxy method volume so no need to add( and later have to maintain) an extra method get_volume for this sole purpose.

https://ruby-doc.org/core-2.1.1/Module.html#method-i-attr_reader

Comments

0

You should use attr_reader :volume instead of using get_volume method. Stil attr_reader and your method get_volume both are functioning same. Generally get_ methods should be avoided in ruby.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.