Skip to content

Instantly share code, notes, and snippets.

@kevbuchanan
Last active August 29, 2015 14:18
Show Gist options
  • Save kevbuchanan/d49513d169cf803e445c to your computer and use it in GitHub Desktop.
Save kevbuchanan/d49513d169cf803e445c to your computer and use it in GitHub Desktop.
Ruby Optional Proc
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