Ruby Newbie homepage Ruby Newbie homepage

How to use

Quick guide

Official content
Iterates over array elements.
When a block given, passes each successive array element to the block; returns self:
a = [:foo, 'bar', 2]
a.each {|element|  puts "#{element.class} #{element}" }
Output:
Symbol foo
String bar
Integer 2
Allows the array to be modified during iteration:
a = [:foo, 'bar', 2]
a.each {|element| puts element; a.clear if element.to_s.start_with?('b') }
Output:
foo
bar
When no block given, returns a new Enumerator:
a = [:foo, 'bar', 2]
e = a.each
e # => #<Enumerator: [:foo, "bar", 2]:each>
a1 = e.each {|element|  puts "#{element.class} #{element}" }
Output:
Symbol foo
String bar
Integer 2
 
               VALUE
rb_ary_each(VALUE ary)
{
    long i;
    ary_verify(ary);
    RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
    for (i=0; i<RARRAY_LEN(ary); i++) {
        rb_yield(RARRAY_AREF(ary, i));
    }
    return ary;
}
            

Was this page useful?