Enter (amper)Sandman

A TL;DR version of ampersand usage with enumerable objects and what we can pass with it.

We all love our friend the ampersand when it comes to iterating over enumerable objects. But with what can we use them? The most obvious and well known is to send a method to the object currently being looked at:

users.map(&:name)
# => ['Jack', 'Jill', 'Gladys']

You can also create and pass local procs and lambdas to pass through and execute on each iteration:

procasaurus = Proc.new do |val|
  val.name
end

users.map(&procasaurus)
# => ['Jack', 'Jill', 'Gladys']

This "call"s the proc / lambda to execute it.

But what about local methods? For lots of reasons, readability and easy documentation being a couple of the main ones, when it doesn't make sense to have a method inside the object class being iterated over I don't really want to be writing local procs all over the place, but if we do this:

def my_method(val)
  val.name
end

users.map(&my_method)
# => ArgumentError: wrong number of arguments (0 for 1)

Things dont go as hoped, because we execute the method on its own, we don't "call" it, but we can! and here is where the #method method comes to the rescue! We can "call" methods with it:

def my_method(val)
  val.name
end

method(:my_method).call(users.first)
# => 'Jack'

Meaning we can do the same when passing it to the iterating method:

def my_method(val)
  val.name
end

users.map(&method(:my_method))
# => ['Jack', 'Jill', 'Gladys']

Now we can have nice properly defined methods instead of nasty locally defined Procs / Lambdas. Hooray!

Profile picture

SNS

Contact Me

  • john.hayes.reed@gmail.com

Recent Activity

Attended Kansai Ruby Kaigi 2017

A Ruby conference in the kansai region of japan, held in Osaka. Listened to a variety of presentations from many people in the Ruby community. This years theme was Community and Business.

Bottled observers gem release

The first production version of bottled_observers has been released (v0.1.0)


New blog post!

A blog about more advanced decorating concepts in ruby.


Bottled decorators gem update

v0.1.5 of bottled decorators has been released.


New blog post!

A blog post about the concept of class-instance variables


Website Design Update

johnhayesreed.com has had a makeover with Bootstrap 4

New blog post!

A new blog about design patterns in rails - Decorators


Bottled decorators gem release

The first production version of bottled_decorators has been released (v0.1.4)


New blog post!

A new blog about desing patterns in rails - Services


Bottled services gem release

The first production version of bottled_services has been released (v0.1.3)


Ruby Rampage 2016

Took part in 2016's Ruby Rampage 48 hour Hackathon.