如何将类的实例添加到另一个类(Ruby)的数组中
我的目录中有两个文件,一个是garage.rb
&另一个称为car.rb
。
car.rb
文件只保存一个汽车对象:
class Car
end
garage.rb
文件如下:
require 'car.rb' #Makes car class accessible in garage.rb
class Garage
def initialize
@capacity = []
end
attr_accessor :capacity
end
当我通过调用car
的新实例时car = car.new
,如何将car
对象放在@capacity
array array my my默认值中?
本质上,每当我调用car = car.new
时,我都希望将car
立即放在@capacity
array中。
我了解我可以做出这样的函数:
def add_car_to_garage(car)
capacity << car
end
但是,我希望汽车在创建车库时在车库中启动,所以我不希望方法将其添加到数组中,我只希望它自动从此开始创建CAR
的实例。
任何建议将不胜感激。谢谢。
I have two files in my directory, one which is garage.rb
& another called car.rb
.
car.rb
file just holds a car object:
class Car
end
garage.rb
file is as follows:
require 'car.rb' #Makes car class accessible in garage.rb
class Garage
def initialize
@capacity = []
end
attr_accessor :capacity
end
When I make a new instance of a car
by calling car = Car.new
, how do I put car
object in the @capacity
array my default?
Essentially, whenever I call car = Car.new
, I want car
to be put in the @capacity
array instantly.
I understand that I could make a function like so:
def add_car_to_garage(car)
capacity << car
end
But, I want the car to start in the garage when it is created, so I don't want a method to add it to the array, I just want it to automatically start there when the instance of car
is created.
Any advice would be appreciated. Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
objectspace
与 every_objectCAR
类中的方法定义方法以跟踪每个生活实例,例如:还请注意,我使用
require_relative
来包括<代码> car.rb 类别在同一目录中。编辑评论问题和Cary Swoveland建议:
另外,我删除了
attr_accessor:apcation
,因为在这种情况下您不需要它。You can use the
ObjectSpace
module with each_object method inside yourCar
class to define method to keep track for each living instances, like this:Also note, I have used
require_relative
to includecar.rb
class which is in the same directory.Edit for comment question and Cary Swoveland suggestion:
Also note, I removed
attr_accessor :capacity
, since you don't need it in this case.CAR
的实例收集应由该类保留和维护,并根据需要提供给其他类。可以如下完成。创建类
car
初始化类实例变量@cars
并为其创建一个getter,cars :: cars :: cars
,后者通过调用attr_reader
oncar
的Singleton类。让我们创建一辆汽车:
然后
创建另一辆车。
然后
卸下汽车。
然后,
要使类实例变量
@cars
可用于车库
添加一个简单实例方法的实例:in
car
可以写作。
The collection of instances of
Car
should be kept and maintained by that class and made available to other classes as needed. That can be done as follows.The creation of the class
Car
initializes the class instance variable@cars
and creates a getter for it,Cars::cars
, the latter by invokingattr_reader
onCar
's singleton class.Let's create a car:
Then
Create another car.
Then
Now remove a car.
Then
To make the class instance variable
@cars
available to instances ofGarage
add a simple instance method:In
Car
can alternatively be written