APIdock / Ruby
/
method

each

ruby latest stable - Class: Range
each()
public

Iterates over the elements of range, passing each in turn to the block.

The each method can only be used if the begin object of the range supports the succ method. A TypeError is raised if the object does not have succ method defined (like Float).

If no block is given, an enumerator is returned instead.

(10..15).each  {|n| print n, '' }
# prints: 10 11 12 13 14 15
(2.5..5).each  {|n| print n, '' }
# raises: TypeError: can't iterate from Float
static VALUE
range_each(VALUE range)
{
 VALUE beg, end;
 RETURN_SIZED_ENUMERATOR(range, 0, 0, range_enum_size);
 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_sym2str(end);
 args[1] = EXCL(range) ? Qtrue : Qfalse;
 rb_block_call(rb_sym2str(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, each_i, 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, 0);
 }
 }
 return range;
}

AltStyle によって変換されたページ (->オリジナル) /