Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

instance method

Array#collect

[T] () { (Elem item) -> T } -> ::Array[T]
() -> ::Enumerator[Elem, ::Array[untyped]]
collect {|element| ... } → new_array
collect → new_enumerator

With a block given, calls the block with each element of self; returns a new array whose elements are the return values from the block:

Example
a = [:foo, 'bar', 2]
a1 = a.map {|element| element.class }
a1 # => [Symbol, String, Integer]

With no block given, returns a new Enumerator.

Related: collect!; see also Methods for Converting.

See also #collect! #clear #bsearch_index #combination also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0