Class: Enumerator

Inherits:
Object
  • Object
show all
Defined in:
lib/with_last/core_ext.rb

Overview

open core class

Instance Method Summary collapse

Instance Method Details

#last?Boolean

Returns whether the enumerator is last.

e = [1,2].to_enum
e.last? # => false
e.next  # => 1
e.last? # => false
e.next  # => 2
e.last? # => true

Returns:

  • (Boolean)


35
36
37
38
39
40
# File 'lib/with_last/core_ext.rb', line 35

def last?
  peek
  false
rescue StopIteration => _e
  true
end

#with_lastObject

Iterates with whether the item is the last item.

[1,2].each.with_last { |item, is_last| puts [item, is_last] }
# => [1, false] [2, true]

[1,2].map.with_last { |item, is_last| "#{item}#{is_last ? '.' : ', '}" }.join
# => "1, 2."

%w[hoge fuga].map.with_index.with_last { |item, index, is_last| "#{index}: #{item}#{is_last ? '.' : ', '}" }.join
# => "0:hoge, 1:fuga."


17
18
19
20
21
22
23
24
# File 'lib/with_last/core_ext.rb', line 17

def with_last
  return to_enum :with_last unless block_given?

  each do |*args|
    self.next
    yield(*args, last?)
  end
end