Class: RubyJS.Enumerable

Defined in: lib/corelib/enumerable.coffee

Overview

Enumerable is a module of iterator methods that all rely on #each for iterating. Classes that include Enumerable are Enumerator, Range, Array. However for performance reasons they are typically re-implemented in them to avoid the extra method calls through #each.

Instance Method Summary

Instance Method Details

- (void) is_enumerable()

- (void) all(block)

Passes each element of the collection to the given block. The method returns true if the block never returns false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is all? will return true only if none of the collection members are false or nil.)

Examples:

  R.w('ant bear cat').all (word) -> word.length >= 3   # => true
  R.w('ant bear cat').all (word) -> word.length >= 4   # => false
  R([ null, true, 99 ]).all()                          # => false

- (void) any(block)

Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of {|obj| obj} (that is any? will return true if at least one of the collection members is not false or nil.

R.w('ant bear cat').any (word) -> word.length >= 3   # => true
R.w('ant bear cat').any (word) -> word.length >= 4   # => true
R([ null, true, 99 ]).any()                          # => true

- (void) collect_concat(block = null)

Returns a new array with the concatenated results of running block once for every element in enum.

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

@alias #flat_map

Examples:

 R([[1,2],[3,4]]).flat_map (i) -> i   #=> [1, 2, 3, 4]

- (void) count(block)

Returns the number of items in enum, where size is called if it responds to it, otherwise the items are counted through enumeration. If an argument is given, counts the number of items in enum, for which equals to item. If a block is given, counts the number of elements yielding a true value.

@execute ary = R([1, 2, 4, 2]) ary.count() #=> 4 ary.count(2) #=> 2 ary.count (x) -> x%2 == 0 #=> 3

- (void) cycle(n, block)

TODO: does not rescue StopIteration

Calls block for each element of enum repeatedly n times or forever if none or nil is given. If a non-positive number is given or the collection is empty, does nothing. Returns nil if the loop has finished without getting interrupted.

cycle saves elements in an internal array so changes to enum after the

first pass have no effect.

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

Examples:

  a = R(["a", "b", "c"])
  a.cycle (x) -> R.puts x      # print, a, b, c, a, b, c,.. forever.
  a.cycle(2) (x) -> R.puts x   # print, a, b, c, a, b, c.

- (void) drop(n)

Drops first n elements from enum, and returns rest elements in an array.

Examples:

  a = R([1, 2, 3, 4, 5, 0])
  a.drop(3)             #=> [4, 5, 0]

- (void) drop_while(block)

Drops elements up to, but not including, the first element for which the block returns nil or false and returns an array containing the remaining elements.

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

Examples:

  a = R([1, 2, 3, 4, 5, 0])
  a.drop_while (i) -> i < 3    #=> [3, 4, 5, 0]

- (void) each_cons(args...)

Iterates the given block for each array of consecutive elements. If no block is given, returns an enumerator.

Examples:

   R.rng(1,6).each_cons 3, (a) -> R.puts a
   # output:
   # [1, 2, 3]
   # [2, 3, 4]
   # [3, 4, 5]
   # [4, 5, 6]

- (void) each_entry(block)

Calls block once for each element in self, passing that element as a parameter, converting multiple values from yield to an array.

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

- (void) each_slice(n, block)

Iterates the given block for each slice of elements. If no block is given, returns an enumerator.

Examples:

  (1..10).each_slice(3) {|a| p a}
  # outputs below
  [1, 2, 3]
  [4, 5, 6]
  [7, 8, 9]
  [10]

- (void) each_with_index(block)

Calls block with two arguments, the item and its index, for each item in enum. Given arguments are passed through to each().

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

Examples:

  hsh = {}
  R.w('cat dog wombat').each_with_index (item, index) ->
    hsh[item] = index
  hsh   #=> {"cat"=>0, "dog"=>1, "wombat"=>2}

- (void) each_with_object(obj, block)

Iterates the given block for each element with an arbitrary object given, and returns the initially given object.

If no block is given, returns an enumerator.

Examples:

  evens = R.rng(1,10).each_with_object [], (i, a) -> a.push(i*2)
  #=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

- (void) find(ifnone, block = null)

Passes each entry in enum to block. Returns the first for which block is not false. If no object matches, calls ifnone and returns its result when it is specified, or returns nil otherwise.

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

@alias #detect

Examples:

  R.rng(1, 10 ).detect (i) -> i % 5 == 0 and i % 7 == 0   #=> nil
  R.rng(1, 100).detect (i) -> i % 5 == 0 and i % 7 == 0   #=> 35

- (void) find_all(block)

Returns an array containing all elements of enum for which block is not false (see also Enumerable#reject).

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

Examples:

  R.rng(1,10).find_all (i) ->  i % 3 == 0    #=> [3, 6, 9]

- (void) find_index(value)

Compares each entry in enum with value or passes to block. Returns the index for the first for which the evaluated value is non-false. If no object matches, returns nil

If neither block nor argument is given, an enumerator is returned instead.

Examples:

  R.rng(1,10).find_index  (i) -> i % 5 == 0 and i % 7 == 0   #=> nil
  R.rng(1,100).find_index (i) -> i % 5 == 0 and i % 7 == 0   #=> 34
  R.rng(1,100).find_index(50)                                #=> 49

- (void) first(n = null)

Returns the first element, or the first n elements, of the enumerable. If the enumerable is empty, the first form returns nil, and the second form returns an empty array.

Examples:

  R.w('foo bar baz').first()   #=> "foo"
  R.w('foo bar baz').first(2)  #=> ["foo", "bar"]
  R.w('foo bar baz').first(10) #=> ["foo", "bar", "baz"]
  new R.Array([]).first()                  #=> null

- (void) include(other)

Returns true if any member of enum equals obj. Equality is tested using ==.

- (void) inject(init, sym, block)

TODO: implement inject('+')

Combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.

If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element. If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method.

If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo.

Examples:


  # Sum some numbers
  # R.rng(5, 10).reduce(:+)                            #=> 45
  # Same using a block and inject
  R.rng(5, 10).inject {|sum, n| sum + n }            #=> 45
  # Multiply some numbers
  R.rng(5, 10).reduce(1, :*)                         #=> 151200
  # Same using a block
  R.rng(5, 10).inject(1) {|product, n| product * n } #=> 151200
  # find the longest word
  longest = R.w('cat sheep bear').inject (memo,word) ->
     if memo.length > word.length then memo else word
  # longest                                       #=> "sheep"

- (void) grep(pattern, block)

Returns an array of every element in enum for which Pattern === element. If the optional block is supplied, each matching element is passed to it, and the block’s result is stored in the output array.

Examples:

  R.rng(1, 100).grep R.rng(38,44)   #=> [38, 39, 40, 41, 42, 43, 44]

- (void) group_by(block)

Returns a hash, which keys are evaluated result from the block, and values are arrays of elements in enum corresponding to the key.

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

Examples:

   R.rng(1, 6).group_by (i) -> i%3
   #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}

- (void) map(block)

Returns a new array with the results of running block once for every element in enum.

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

@alias #collect

Examples:

  R.rng(1, 4).collect (i) -> i*i   #=> [1, 4, 9, 16]
  R.rng(1, 4).collect -> "cat"     #=> ["cat", "cat", "cat", "cat"]

#map with an enumerator:


 en = R(['a']).each_with_index() #=> ['a', 0]
 en.map (x) ->   # x: 'a'
 en.map (x,i) -> # x: 'a', i: 0
 en.map (x...) -> # x: ['a', 0]

- (void) max(block)

Returns the object in enum with the maximum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.

@return a = R.w('albatross dog horse') a.max() #=> "horse"

# Not recommended at the moment:
a.max (a,b) -> R(a.length)['<=>'] b.length }   #=> "albatross"

- (void) max_by(block)

Returns the object in enum that gives the maximum value from the given block.

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

Examples:

  a = R.w('albatross dog horse')
  a.max_by (x) -> x.length    #=> "albatross"

- (void) min(block)

Returns the object in enum with the minimum value. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.

a = R.w('albatross dog horse')
a.min()                                  #=> "albatross"
# Not recommended at the moment:
a.min (a,b) -> R(a.length)['<=>'] b.length }   #=> "dog"

- (void) min_by(block)

Returns the object in enum that gives the minimum value from the given block.

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

Examples:

  a = R.w('albatross dog horse')
  a.min_by (x) -> x.length   #=> "dog"

- (void) minmax(block)

Returns two elements array which contains the minimum and the maximum value in the enumerable. The first form assumes all objects implement Comparable; the second uses the block to return a <=> b.

Examples:

  a = R.w('albatross dog horse')
  a.minmax()                                  #=> ["albatross", "horse"]
  a.minmax (a,b) -> a.length <=> b.length }   #=> ["dog", "albatross"]

- (void) minmax_by(block)

- (void) none(block)

Passes each element of the collection to the given block. The method returns true if the block never returns true for all elements. If the block is not given, none? will return true only if none of the collection members is true.

Examples:

  R.w('ant bear cat').none (word) -> word.length == 5   # => true
  R.w('ant bear cat').none (word) -> word.length >= 4   # => false
  new R.Array([]).none()                                          # => true
  R([nil]).none()                                       # => true
  R([nil,false]).none()                                 # => true

- (void) one(block)

Passes each element of the collection to the given block. The method returns true if the block returns true exactly once. If the block is not given, one? will return true only if exactly one of the collection members is true.

Examples:

  R.w('ant bear cat').one (word) -> word.length == 4   # => true
  R.w('ant bear cat').one (word) -> word.length > 4    # => false
  R.w('ant bear cat').one (word) -> word.length < 4    # => false
  R([ nil, true, 99 ]).one()                           # => false
  R([ nil, true, false ]).one()                        # => true

- (void) partition(block)

- (void) reject(block)

- (void) reverse_each(block)

- (void) slice_before(args...)

- (void) sort(block)

- (void) sort_by(block)

- (void) take(n)

- (void) take_while(block)

- (void) to_a()

- (void) to_enum(iter = "each", args...)

- (void) zip(others...)

TODO: recursive arrays Untested
TODO: uses #each to extract arguments' elements when #to_ary fails
TODO: dont yield R.Arrays

Takes one element from enum and merges corresponding elements from each args. This generates a sequence of n-element arrays, where n is one more than the count of arguments. The length of the resulting sequence will be enum#size. If the size of any argument is less than enum#size, nil values are supplied. If a block is given, it is invoked for each output array, otherwise an array of arrays is returned.

Examples:

  a = R([ 4, 5, 6 ])
  b = R([ 7, 8, 9 ])
  R([1,2,3]).zip(a, b)      #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
  R([1,2]  ).zip(a,b)       #=> [[1, 4, 7], [2, 5, 8]]
  a.zip([1,2],[8])           #=> [[4, 1, 8], [5, 2, nil], [6, nil, nil]]