Skip to content

Instantly share code, notes, and snippets.

@Ebtoulson
Created September 17, 2013 16:35
Show Gist options
  • Save Ebtoulson/6596907 to your computer and use it in GitHub Desktop.
Save Ebtoulson/6596907 to your computer and use it in GitHub Desktop.
# If you were curious how to do it with lambdas,
# I think this way makes the method definition look ugly but w/e
def method(arr, fn = ->(e){ "" })
arr[:no_key]
rescue => e
fn.call(e)
end
method([])
# => ""
method([], ->(e){ raise e })
# TypeError: can't convert Symbol into Integer
@jaredbranum
Copy link

you can do it with a block like so:

def method(arr, &block)
  block ||= ->(e){ "" }
  arr[:no_key]
rescue => e
  block.call e
end

method([])
# => ""

method([]) {|e| raise e }
# TypeError: can't convert Symbol into Integer

the definition is slightly longer since you have to assign a lambda to block if one isn't passed, but i like that you can call it with a block

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment