Last active
August 19, 2016 14:41
-
-
Save tiagopog/54e632a06f78fbdc6d0a to your computer and use it in GitHub Desktop.
Ruby - Enumerator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def print_enum(enum) | |
puts enum | |
puts enum.inspect | |
end | |
# Example: 1 | |
enum = %w(foo bar).each | |
print_enum(enum) | |
3.times { puts enum.next } rescue nil | |
print_enum(enum) | |
# Example: 2 | |
enum2 = %w(a b c d e).each | |
print_enum(enum2) | |
enum2.each_with_object('letter') do |item, obj| | |
puts "#{obj}: #{item}" | |
end | |
while e = enum2.next | |
puts e | |
end | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
# Enumerator#lazy | |
## | |
enum = | |
{ name: 'Tiago Guedes', email: '[email protected]' } | |
.lazy | |
.map { |(key, value)| puts key; [key, value] } | |
.find { |e| e[1] == 'Tiago Guedes' } | |
#=> name | |
puts enum[1] #=> Tiago Guedes | |
## | |
# Enumerator#yield | |
## | |
enum = Enumerator.new do |e| | |
map_find = | |
{ name: 'Tiago Guedes', email: '[email protected]' } | |
.map { |(key, value)| puts key; [key, value] } | |
.find { |e| e[1] == 'Tiago Guedes' } | |
e.yield map_find | |
end | |
#=> name | |
enum.each { |e| puts e[1] } #=> Tiago Guedes |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[1, 3, 2, 4, 5, 6].chunk { |e| e.even? }.each { |result, array| print array; print ',' } #=> [1, 3],[2, 4],[5],[6],=> nil | |
'foo bar foobar'.split.sort.chunk { |e| e.ord }.each { |result, array| print "#{array.first[0]} - #{array.length}"; print ',' } #=> b - 1,f - 2,=> nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment