如何创建对象数组? [英] How to create array of objects?

查看:72
本文介绍了如何创建对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何像下面的C ++示例一样创建对象数组?

How to create an Array of objects like the below C++ example?

Ruby进行 Print print [1000]; 的方式是什么?

What's the Ruby way of doing Print print[1000];?

下面的代码是C ++。我只是想知道Ruby是否可以实例化一个类的1000个唯一对象:

The below code is C++. I'm just wondering if Ruby has an option to instantiate 1000 unique objects of a class:

class Print
{

public:
    Print()
    {
        static int count = 0;
        cout<<"h"<<++count<<endl;
    }
};

int main()
{    
    Print print[1000];
    getchar();
    return 0;
}


推荐答案

要获取1000份实例化字符串,我们可以这样做:

To get 1000 copies of a string instantiated, we can do this:

collection_of_strings = Array.new(1000, String.new('h'))
print collection_of_strings

这是存储在数组中的同一对象。然后打印出该数组。

This is the same object stored in the array. And then that array printed.

这种形式的Array.new带有给定的块将创建一个单独实例化的对象,但是您多次为该参数指定

This form of Array.new with the block given will create an individually instantiated object, however many times you gave for the argument:

>> collection = Array.new(10) {String.new}   
=> ["", "", "", "", "", "", "", "", "", ""] 

和通过检查数组中每个对象的 object_id 来证明。

And the proof by checking object_id of each object in the array.

>> collection.each {|e| puts e.object_id}    
85621980                                     
85621970                                     
85621960                                     
85621950                                     
85621940                                     
85621930                                     
85621920                                     
85621910                                     
85621900                                     
85621890                                     
=> ["", "", "", "", "", "", "", "", "", ""]  

这篇关于如何创建对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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