https://github.com/oieioi/with_last.rb
💎 Enumerable#each_with_last and Enumerator#with_last
https://github.com/oieioi/with_last.rb
ruby
Last synced: 9 months ago
JSON representation
💎 Enumerable#each_with_last and Enumerator#with_last
- Host: GitHub
- URL: https://github.com/oieioi/with_last.rb
- Owner: oieioi
- License: mit
- Created: 2019-12-24T09:59:38.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2020-03-04T03:44:59.000Z (over 6 years ago)
- Last Synced: 2025-10-09T03:19:34.875Z (9 months ago)
- Topics: ruby
- Language: Ruby
- Homepage: https://rubygems.org/gems/with_last
- Size: 20.5 KB
- Stars: 4
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
[](https://badge.fury.io/rb/with_last)

# with_last.rb
- Add `with_last` method to `Enumerator` class.
- Add `last?` method to `Enumerator` class.
- Add `each_with_last` to `Enumerable` module.
## Installation
```ruby
gem 'with_last'
```
And then execute:
$ bundle install
## Usage
### `Enumerable#each_with_last`
```ruby
[1,2,3].each_with_last { |item, last|
print "#{item}#{last ? '!' : ' => '}"
}
```
it prints `1 => 2 => 3!`
### `Enumerator#with_last`
```ruby
[1,2,3]
.map
.with_last { |item, last| "#{item * item}#{last ? '.' : ''}" }
.join(',')
```
it returns `"1,4,9."`
### `Enumerator#last?`
```ruby
e = [1,2].to_enum
e.last? # => false
e.next # => 1
e.last? # => false
e.next # => 2
e.last? # => true
```
### in ERB
```erb
<% %w[hoge fuga piyo].each_with_last do |item, is_last| %>
<%= item %><%= is_last ? '.' : ', ' %>
<% end %>
```
it renders;
```html
hoge, fuga, piyo.
```
## License
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).