Last active
August 29, 2015 14:21
-
-
Save KamilLelonek/636c3277bb4fd597fc51 to your computer and use it in GitHub Desktop.
Lazy evaluation example in Ruby
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] (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