Skip to content

Instantly share code, notes, and snippets.

@KamilLelonek
Last active August 29, 2015 14:21
Show Gist options
  • Save KamilLelonek/636c3277bb4fd597fc51 to your computer and use it in GitHub Desktop.
Save KamilLelonek/636c3277bb4fd597fc51 to your computer and use it in GitHub Desktop.
Lazy evaluation example in Ruby
[1] (pry) main: 0> { key: :val }.fetch(:key, raise('Key does not exist'))
RuntimeError: Key does not exist
[2] (pry) main: 0> { key: :val }.fetch(:key) { raise('Key does not exist') }
=> :val
[3] (pry) main: 0> Array.new(3, rand(10))
=> [0, 0, 0]
[4] (pry) main: 0> Array.new(3) { rand(10) }
=> [3, 1, 5]
[5] (pry) main: 0> %i(a b c).map { |symbol| puts symbol }.detect { true }
a
b
c
=> nil
[6] (pry) main: 0> %i(a b c).lazy.map { |symbol| puts symbol }.detect { true }
a
=> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment