new(p1 = v1, p2 = v2)
public
Returns a new array. In the first form, the new array is empty. In the second it is
created with size copies of
obj (that is, size
references to the same obj). The third form creates a copy of the
array passed as a parameter (the array is generated by calling to_ary on the parameter). In the last form, an array of the given size is created. Each element in this array is
calculated by passing the element’s index
to the given block and storing the return value.
Array.new
Array.new(2)
Array.new(5, "A")
a = Array.new(2, Hash.new)
a[0]['cat'] = 'feline'
a
a[1]['cat'] = 'Felix'
a
a = Array.new(2) { Hash.new }
a[0]['cat'] = 'feline'
a
squares = Array.new(5) {|i| i*i}
squares
copy = Array.new(squares)
Show source
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) && RARRAY_PTR(ary)) {
xfree(RARRAY_PTR(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);
if (len < 0) {
rb_raise(rb_eArgError, "negative array size");
}
if (len > ARY_MAX_SIZE) {
rb_raise(rb_eArgError, "array size too big");
}
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 {
memfill(RARRAY_PTR(ary), len, val);
ARY_SET_LEN(ary, len);
}
return ary;
}