如何调用一个类的实例,实例方法从不同的类
问题描述:
所以,我有以下设置如何调用一个类的实例,实例方法从不同的类
class foo
:attr_accessor :textBoxInFoo
@textBoxInFoo
def appendText
//appends text to textBoxInFoo
end
def getLastPartOfText
//gets the last line of text in textBoxInFoo
end
end
class bar
def UseFoo
//Declares instance of textBoxInFoo
end
end
class snafu
def runInBackground
//Needs to read and write from instance of textBoxInFoo in bar class
end
end
什么,我没有完全理解是怎么做我需要在runInBackground做为了让它阅读和写入textBoxInFoo,我一直在阅读实例和类方法的各种解释,而且他们中没有人真的点击过我,所以我想知道是否有人知道我搞乱了什么。
答
这是如何创建用户对象并将其作为参数发送给学生对象的一个小例子。 run()方法调用用户的运行方法。
class User
attr_accessor :name
def initialize(name) # it is similar to constructor
@name = name
end
#run method
def run
puts "I am running"
end
#getter for name
def get_name
@name
end
#setter for name
def set_name=(name)
@name = name
end
end
class Student
attr_accessor :obj
def initialize(obj)
@obj = obj
end
def run
obj.run
puts "inside of Student"
end
end
user = User.new("John")
stud = Student.new(user)
stud.run # shows I am running
# inside of student
这是有点混乱,你一直在谈论textBoxInFoo的实例,但似乎没有这样的类。这些类如何相互关联?此外,你的代码是不是有效的红宝石 - 这可能与你的问题相切,但它绝对是一个分心 –
通常,你创建一个类的实例(即现在是该类的一个对象),该实例可以使用实例变量和该类的方法。在你的情况下,你试图访问另一个类'snafu'中的实例变量。但为了访问'@ textBoxInFoo',你应该首先实例化一个类'foo'的实例。因此,例如,在'runInBackground'中,您将创建一个新的实例'text = foo.new',然后您可以访问实例变量'text.textBoxInFoo'。 –
在'RunInBackground'中,您可以使用'Foo.new.textBoxInFoo'创建一个到另一个对象的本地引用。如果你不想初始化'Foo',那么你可以创建一个'Foo :: TextBoxInFoo'常量。顺便说一下,你的类名需要以大写字母开头。 –