Skip to content

Instantly share code, notes, and snippets.

@dkinzer
Created November 2, 2017 03:42
Show Gist options
  • Save dkinzer/a4e78c807dd38b0a33971306c66c5e33 to your computer and use it in GitHub Desktop.
Save dkinzer/a4e78c807dd38b0a33971306c66c5e33 to your computer and use it in GitHub Desktop.
def block_or_proc(block = Proc.new {|*args|})
if block_given?
block = Proc.new { |*args| yield args }
end
block
end
# Using blocks with no additional args.
a = block_or_proc { puts "hello" }
a.call
# Outputs: "hello"
# Using procs with no addtional args.
p = Proc.new { puts "goodbye "}
b = block_or_proc(p)
b.call
# Outputs: "goodbye"
# Using procs with args.
p = Proc.new { |x, y| x + y }
c = block_or_proc(p)
puts c.call(3, 4)
# Outputs: 7
# Using procs with more args.
d = block_or_proc { |x, y, z| x + y + z }
puts d.call(3, 4, 1)
# Outputs: 8
# Not passing anything.
e = block_or_proc
puts (e.call).class
# Outpus: NilClass
# Still works with `&`?
f = block_or_proc(&p)
puts f.call(4, 5)
# Outputs: 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment