Ruby: Accessing class instance variables from one class in another class's class method
I am working on a ruby program and have run into the following problem.
I have two classes AClass and BClass as follows:
class AClass
attr_accessor :avar
def initialize(input)
@avar = input
end
end
class BClass
def BClass.build(aclass)
bvalue = aclass.avar
....
end
end
When i run:
aclass = AClass.new
puts aclass.avar
bclass = BClass.build(aclass)
The first two lines work fine. aclass is intialized and avar is put out to the screen, but the third line creates an error. I seems that the BClass build method can not access the AClass instance variable. What do I need to do to make this work.开发者_JAVA技巧 I thought the attr_accessor would enable me to access the AClass instance variables. Thanks in advance for your input.
If you want to create a new type of initializer for BClass, you can do the following:
class AClass
attr_accessor :avar
def initialize(input)
@avar = input
end
end
class BClass
attr_accessor :bvalue
def self.build(aclass)
bclass = self.new
bclass.bvalue = aclass.avar
bclass
end
end
aclass = AClass.new 'ruby'
bclass = BClass.build aclass
This will set bclass.bvalue = aclass.avar = 'ruby'.
Mutu, you need to learn the basics of ruby... what you have there is not even valid ruby code.
try running this.
class AClass
attr_accessor :avar
def initialize(input)
@avar = input
end
end
class BClass
attr_reader :bvalue
def initialize(aclass)
@bvalue = aclass.avar
end
end
in irb
ruby-1.9.2-p136 :077 > a = AClass.new('ruby')
=> #<AClass:0x00000100997298 @avar="ruby">
ruby-1.9.2-p136 :078 > b = BClass.new(a)
=> #<BClass:0x000001009921d0 @bvalue="ruby">
ruby-1.9.2-p136 :079 > b.bvalue
=> "ruby"
ruby-1.9.2-p136 :080 > a.avar
=> "ruby"
精彩评论