Accessing varible in ruby after initialization
I am trying to access a variable in ruby after initialization, but I didn't get this variable, is there something wrong with 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
+3
source to share
2 answers
You should probably set up the accessory for the attributes and then use them like this:
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
+2
source to share
You are mixing instance and class method in your example. If this is indeed what you want, then you should 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)
This instance / class-error method is an error, then this example can 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 also define accessors, as in the first code, then you are accessing from outside the class again.
Just in case you don't want a reader, see also Accessing an Instance Outside a Class
+1
source to share