使用顺序名称创建和初始化类的实例 [英] Create and initialize instances of a class with sequential names

查看:114
本文介绍了使用顺序名称创建和初始化类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 BankAccount 类.我试图创建此类的多个实例,并将它们放入数组中.例如

I have a BankAccount class. I was trying to create multiple instances of this class and put them into an array. For example

accounts = [Ba1 = BankAccount.new(100), Ba2 = BankAccount.new(100)]

我想用大量实例(例如20个)初始化数组,所以从 Ba1 Ba20 .有没有比手动输入更简单的方法呢?我已经尝试了一个循环,但是我只是想不通如何使之工作.

I want to initialize the array with a large number of instances inside, let's say 20, so from Ba1 to Ba20. Is there an easier way to do it instead of just manually inputting it? I have tried a loop but I just can't figure out how to make it work.

推荐答案

这应该可以解决问题:

accounts = 100.times.collect { BankAccount.new(100) }

如果您需要根据每个帐户的不同来执行不同的操作,则:

If you need to do something different for each account based on which one it is then:

accounts = 100.times.collect { |i| BankAccount.new(i) }

i 表示要迭代的集合中的每个数字.

i represents each number in the collection being iterated over.

如果您实际上需要使用数据设置变量名,则可以调用 eval().

If you actually need to set the variable names using the data you can call eval().

accounts = 100.times.collect { |i| eval("B#{i} = BankAccount.new(100)") }

现在应将 B1 B100 设置为适当的BankAccount实例.

And now B1 through B100 should be set to the appropriate BankAccount instances.

免责声明:我应该说,这种方法通常会被反对.在这种情况下,您已经有一个名为accounts的数组.您需要做的就是索引它以获得相应的银行帐户.例如,以 accounts [50] 代替 Ba50 .在红宝石开发的这些年里,我发现很少有地方可以使用eval.

Disclaimer: I should say that this approach will be generally frowned upon. In this case you already have an array called accounts. All you need to do is index on it to get the corresponding bank account. accounts[50] for example instead of Ba50. In my years of ruby development I've found few places to use eval that made sense.

这篇关于使用顺序名称创建和初始化类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆