Last active
August 29, 2015 14:18
-
-
Save kevbuchanan/d49513d169cf803e445c to your computer and use it in GitHub Desktop.
Ruby Optional Proc
This file contains 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 call_maybe(x) | |
if block_given? | |
yield x | |
else | |
x | |
end | |
end | |
call_maybe(2) { |x| x + 1 } | |
call_maybe(2) | |
=begin | |
This doesn't work | |
def call_maybe(x, &block = nil) | |
if block | |
block.call(x) | |
else | |
x | |
end | |
end | |
=end | |
def call_maybe(y, fn = nil) | |
if fn | |
fn.call(y) | |
else | |
y | |
end | |
end | |
call_maybe(1, ->(y) { y + 1 }) | |
call_maybe(1) | |
def call_for_sure(z, fn = ->(z) { z + 1 }) | |
fn.call(z) | |
end | |
call_for_sure(1) | |
call_for_sure(1, ->(z) { z - 1 }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment