0

I am working with a 3rd party library where I'm trying to access a class member variable but unfortunately there is also a method with the same name.

class Test
  attr_writer :var

  def var
    "some other stuff that is not var"
  end
end

test = Test.new()

# Returns result of function but I need variable contents
test.var

Unfortunately I cannot change this since it's 3rd party.

Vincent
  • 2,342
  • 1
  • 17
  • 22
  • I really don't understand what you're trying to do..? – 13aal Dec 11 '15 at 20:20
  • This question doesn't make sense. Instance variables and methods have different namespaces, instance variables *always* start with `@`, methods *never* start with `@`, there *cannot* possibly be a name collision. – Jörg W Mittag Dec 12 '15 at 02:06

2 Answers2

2

You could use instance_variable_get:

test = Test.new
test.instance_variable_get(:@var)
spickermann
  • 100,941
  • 9
  • 101
  • 131
0

You can add a reader-method with other name:

class Test
   def var_reader
       @var
   end
end

This may be better, than directly using instance_variable_get, if you need it more than once or may need some additional logic around

On ruby-2.1+ this can be more elegant with a refinement:

module TestRefinement
  refine Test do
    def var_getter
      @var
    end
  end
end

using TestRefinement
a.var_getter
Vasfed
  • 18,013
  • 10
  • 47
  • 53