Skip to content

Instantly share code, notes, and snippets.

@wycats
Created March 2, 2013 01:53
Show Gist options
  • Save wycats/5069291 to your computer and use it in GitHub Desktop.
Save wycats/5069291 to your computer and use it in GitHub Desktop.
Lazy enumerations reduce allocations
class LoggedChar < Struct.new(:char)
def downcase
puts "downcasing #{char}"
char.downcase
end
def capitalized?
puts "capitalized? #{char}"
char =~ /[A-Z]/
end
end
array = %w(a B c D e F g).map { |char| LoggedChar.new(char) }
puts "## NORMAL ITERATION ##"
puts
p array.select(&:capitalized?).map(&:downcase)
puts
puts
puts "## LAZY ITERATION ##"
puts
p array.lazy.select(&:capitalized?).map(&:downcase).to_a
# OUTPUT
# ------
#
# ## NORMAL ITERATION ##
#
# capitalized? a
# capitalized? B
# capitalized? c
# capitalized? D
# capitalized? e
# capitalized? F
# capitalized? g
# downcasing B
# downcasing D
# downcasing F
# ["b", "d", "f"]
#
#
# ## LAZY ITERATION ##
#
# capitalized? a
# capitalized? B
# downcasing B
# capitalized? c
# capitalized? D
# downcasing D
# capitalized? e
# capitalized? F
# downcasing F
# capitalized? g
# ["b", "d", "f"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment