Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Returns a new Array.
With no block and no arguments, returns a new empty Array object.
With no block and a single Array argument array, returns a new Array formed from array:
a = Array.new([:foo, 'bar', 2])
a.class # => Array
a # => [:foo, "bar", 2]
With no block and a single Integer argument size, returns a new Array of the given size whose elements are all nil:
a = Array.new(3)
a # => [nil, nil, nil]
With no block and arguments size and default_value, returns an Array of the given size; each element is that same default_value:
a = Array.new(3, 'x')
a # => ['x', 'x', 'x']
With a block and argument size, returns an Array of the given size; the block is called with each successive integer index; the element for that index is the return value from the block:
a = Array.new(3) {|index| "Element #{index}" }
a # => ["Element 0", "Element 1", "Element 2"]
Raises ArgumentError if size is negative.
With a block and no argument, or a single argument 0, ignores the block and returns a new empty Array.
 
               static VALUE
rb_ary_initialize(int argc, VALUE *argv, VALUE ary)
{
    long len;
    VALUE size, val;

    rb_ary_modify(ary);
    if (argc == 0) {
        if (ARY_OWNS_HEAP_P(ary) && ARY_HEAP_PTR(ary) != NULL) {
            ary_heap_free(ary);
        }
        rb_ary_unshare_safe(ary);
        FL_SET_EMBED(ary);
        ARY_SET_EMBED_LEN(ary, 0);
        if (rb_block_given_p()) {
            rb_warning("given block not used");
        }
        return ary;
    }
    rb_scan_args(argc, argv, "02", &size, &val);
    if (argc == 1 && !FIXNUM_P(size)) {
        val = rb_check_array_type(size);
        if (!NIL_P(val)) {
            rb_ary_replace(ary, val);
            return ary;
        }
    }

    len = NUM2LONG(size);
    /* NUM2LONG() may call size.to_int, ary can be frozen, modified, etc */
    if (len < 0) {
        rb_raise(rb_eArgError, "negative array size");
    }
    if (len > ARY_MAX_SIZE) {
        rb_raise(rb_eArgError, "array size too big");
    }
    /* recheck after argument conversion */
    rb_ary_modify(ary);
    ary_resize_capa(ary, len);
    if (rb_block_given_p()) {
        long i;

        if (argc == 2) {
            rb_warn("block supersedes default value argument");
        }
        for (i=0; i<len; i++) {
            rb_ary_store(ary, i, rb_yield(LONG2NUM(i)));
            ARY_SET_LEN(ary, i + 1);
        }
    }
    else {
        ary_memfill(ary, 0, len, val);
        ARY_SET_LEN(ary, len);
    }
    return ary;
}
            

Was this page useful?