Method: Array#initialize
- Defined in:
- array.c
#new ⇒ Object #new(array) ⇒ Object #new(size, default_value = nil) ⇒ Object #new(size = 0) {|index| ... } ⇒ Object
Returns a new array.
With no block and no argument given, returns a new empty array:
Array.new # => []
With no block and array argument given, returns a new array with the same elements:
Array.new([:foo, 'bar', 2]) # => [:foo, "bar", 2]
With no block and integer argument given, returns a new array containing that many instances of the given default_value
:
Array.new(0) # => []
Array.new(3) # => [nil, nil, nil]
Array.new(2, 3) # => [3, 3]
With a block given, returns an array of the given size
; calls the block with each index
in the range (0...size)
; the element at that index
in the returned array is the blocks return value:
Array.new(3) {|index| "Element #{index}" } # => ["Element 0", "Element 1", "Element 2"]
A common pitfall for new Rubyists is providing an expression as default_value
:
array = Array.new(2, {})
array # => [{}, {}]
array[0][:a] = 1
array # => [{a: 1}, {a: 1}], as array[0] and array[1] are same object
If you want the elements of the array to be distinct, you should pass a block:
array = Array.new(2) { {} }
array # => [{}, {}]
array[0][:a] = 1
array # => [{a: 1}, {}], as array[0] and array[1] are different objects
Raises TypeError if the first argument is not either an array or an integer-convertible object). Raises ArgumentError if the first argument is a negative integer.
Related: see Methods for Creating an Array.
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 |
# File 'array.c', line 1124
static VALUE
rb_ary_initialize(int argc, VALUE *argv, VALUE ary)
{
long len;
VALUE size, val;
rb_ary_modify(ary);
if (argc == 0) {
rb_ary_reset(ary);
RUBY_ASSERT(ARY_EMBED_P(ary));
RUBY_ASSERT(ARY_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;
}
|