Create and initialize instances of a class with se

2020-05-01 09:21发布

问题:

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)]

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.

回答1:

This should do the trick:

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 represents each number in the collection being iterated over.

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)") }

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

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.



标签: ruby arrays