Class: Enumerator

Inherits:
Object show all
Defined in:
lib/mug/bool.rb,
lib/mug/functional.rb

Direct Known Subclasses

Iterator

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.unfold(seed, &blk) ⇒ Enumerator

Creates an Enumerator that can unfold a sequence from a given seed.

The block receives the current seed and should return a two-element array [value, next_seed], or nil to end the sequence.

Examples:

require 'mug/functional'
enum = Enumerator.unfold(1) { |n| [n, n+1] }
enum.take(5)  #=> [1, 2, 3, 4, 5]

Fibonacci sequence

require 'mug/functional'
enum = Enumerator.unfold([0, 1]) { |(a,b)| [a, [b, a+b]] }
enum.take(5)  #=> [0, 1, 1, 2, 3]

End enumeration with nil

require 'mug/functional'
enum = Enumerator.unfold(1) { |n| n <= 3 ? [n, n+1] : nil }
enum.take(5)  #=> [1, 2, 3]

Parameters:

  • seed (Object)

    the initial seed value

Returns:

  • (Enumerator)

    an enumerator that unfolds the sequence

Raises:

  • (ArgumentError)


247
248
249
250
251
252
253
254
255
256
257
# File 'lib/mug/functional.rb', line 247

def unfold(seed, &blk)
  raise ArgumentError, 'no block given' unless block_given?
  Enumerator.new do |y|
    loop do
      result = blk.call(seed)
      break if result.nil?
      value, seed = result
      y << value
    end
  end
end

Instance Method Details

#to_bBoolean

Converts enum to a boolean. Returns true if there are any elements. An enumerator whose size cannot be calculated lazily is assumed to be true.

Returns:

  • (Boolean)

    true if self has any elements (or size is unknown)



149
150
151
# File 'lib/mug/bool.rb', line 149

def to_b
  (s = size).nil? || s.to_b
end