3

I am trying to access variable in ruby after initialize, but i didn't get that variable , anything wrong in that?

class Test
  def initialize(params)
    @has_test = params[:has_test]
    @limit_test = params[:limit_test]
  end
  def self.method1(params)
   Test.new(params)
     #can i get that two instance variable
  end
end
Developer
  • 561
  • 7
  • 29
  • @lurker while technically `@@` is the correct syntax most of the time as it seems in this case class instance variables would be used in place of class variables although I agree it seems he is just mistaking self and would like access to the instance variables for the instance itself. – engineersmnky Jun 01 '15 at 17:49
  • @engineersmnky yes, I agree. I didn't catch that until after my comment. – lurker Jun 01 '15 at 17:51
  • Ruby uses `#` for comments, not `//`. – Nic Jun 01 '15 at 19:03

2 Answers2

2

You should probably set up attribute accessors, then use them this way:

class Test
  attr_accessor :has_test
  attr_accessor :limit_test

  def initialize(params)
    @has_test = params[:has_test]
    @limit_test = params[:limit_test]
  end
  def self.method1(params)
    t = Test.new(params)
    // can i get that two instance variable
    // Yes:
    //   use t.has_test and t.limit_test
  end
end
lurker
  • 56,987
  • 9
  • 69
  • 103
  • 1
    Why did you decide to change `@has_test=` to `self.has_test =`? the only reason I can see for doing this is in the event that the setter performs additional operations beyond setting the instance variable. Otherwise this makes an addition method call that is unnecessary. – engineersmnky Jun 01 '15 at 17:54
  • @engineersmnky out of whim I suppose. I changed it back. – lurker Jun 01 '15 at 17:55
1

You are mixing an instance and a class method in your example. If this is really what you want, then you have to define an accessor with attr_reader:

class Test
  def initialize(params)
    @has_test = params[:has_test]
    @limit_test = params[:limit_test]
  end
  attr_reader :has_test
  attr_reader :limit_test
  def self.method1(params)
   obj = Test.new(params)
   p obj.has_test
   p  obj.limit_test
  end
end

Test.method1(has_test: 1, limit_test: 3)

It the instance/class-method is a mistake, then this example may help you:

class Test
  def initialize(params)
    @has_test = params[:has_test]
    @limit_test = params[:limit_test]
  end
  def method1()
   p @has_test
   p @limit_test
  end
end

obj = Test.new(has_test: 1, limit_test: 3)
obj.method1

If you define also the accessors like in the first code, then you have again access from outside the class.


Just in case you don't want a reader, see also Access instance variable from outside the class

Community
  • 1
  • 1
knut
  • 27,320
  • 6
  • 84
  • 112