Skip to content

Instantly share code, notes, and snippets.

@samjonester
Created March 4, 2019 20:23
Show Gist options
  • Save samjonester/51df72bb8b3eaa0908e0c64f444c42a4 to your computer and use it in GitHub Desktop.
Save samjonester/51df72bb8b3eaa0908e0c64f444c42a4 to your computer and use it in GitHub Desktop.
Blocks, Procs, Lambdas in Ruby
  • blocks {|a| … } & do ... end: closures with loose arity (like js functions) that you can yeild to in a method. All methods can accept a block without any change to their signature. You can yield conditionally if a block is given.
class Foo
  def map
    yield(1,2,3) if block_given?
  end
end

Foo.new.map { |one| ... } # <= doesn't matter that arity is inconsistent
  • lambdas ->(a) {...} & lambda {|a| ...} are anonymous callable objects with strict arity like any other method in ruby.
l = ->(a) { a * 2 }
l.call(5)
l.call(5, 2)  # <= will blow up
  • procs &block, &:method, &lambda, Proc.new {|a| ...} are anonymous callable objects with loose arity (like blocks). A method can explicity accept a “block” in it’s signature by converting it to a callable proc.
[...].map(&:do_something)
&->(a) { ... }

def whatevs(&block)
  block.call(5)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment