Read more

Use a Ruby method like a block or lambda

Henning Koch
September 27, 2011Software engineer at makandra GmbH

Sometimes you want to use a vanilla Ruby method like a block. You can use Object#method Show archive.org snapshot to obtain a method reference that responds to #call:

foo_plus = "foo".method(:+)
foo_plus.call("bar") # => "foobar"
Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

The method reference also understands #to_proc so you can feed it to block-taking methods by prefixing it with &:

printer = method(:puts)
[1, 2, 3].each(&printer) # will print one line per number
Posted by Henning Koch to makandra dev (2011-09-27 11:25)