each()
public
Iterates over the elements rng, passing each in turn to the block. You can only iterate
if the start object of the range supports the succ method (which
means that you can’t iterate over ranges of Float objects).
If no block is given, an enumerator is returned instead.
(10..15).each do |n|
print n, ' '
end
produces:
10 11 12 13 14 15
Show source
static VALUE
range_each(VALUE range)
{
VALUE beg, end;
RETURN_ENUMERATOR(range, 0, 0);
beg = RANGE_BEG(range);
end = RANGE_END(range);
if (FIXNUM_P(beg) && FIXNUM_P(end)) { /* fixnums are special */
long lim = FIX2LONG(end);
long i;
if (!EXCL(range))
lim += 1;
for (i = FIX2LONG(beg); i < lim; i++) {
rb_yield(LONG2FIX(i));
}
}
else if (SYMBOL_P(beg) && SYMBOL_P(end)) { /* symbols are special */
VALUE args[2];
args[0] = rb_sym_to_s(end);
args[1] = EXCL(range) ? Qtrue : Qfalse;
rb_block_call(rb_sym_to_s(beg), rb_intern("upto"), 2, args, sym_each_i, 0);
}
else {
VALUE tmp = rb_check_string_type(beg);
if (!NIL_P(tmp)) {
VALUE args[2];
args[0] = end;
args[1] = EXCL(range) ? Qtrue : Qfalse;
rb_block_call(tmp, rb_intern("upto"), 2, args, rb_yield, 0);
}
else {
if (!discrete_object_p(beg)) {
rb_raise(rb_eTypeError, "can't iterate from %s",
rb_obj_classname(beg));
}
range_each_func(range, each_i, NULL);
}
}
return range;
}