Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

A ruby library for prettier-still anonymous blocks.

tree: b8ff41487c

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 spec
Octocat-spinner-32 .gitignore
Octocat-spinner-32 LICENSE.MIT
Octocat-spinner-32 README.markdown
Octocat-spinner-32 ampex.gemspec
README.markdown

The Ampex (&X) library provides a Metavariable X that can be used in conjunction with the unary ampersand to create anonymous blocks in a slightly more readable way than the default. It was inspired by the clever Symbol#to_proc method which handles the most common case very elegantly, and discussion with Sam Stokes who created an earlier version.

Usage

At its simplest, &X can be used as a drop-in replacement for Symbol#to_proc:

[1,2,3].map &X.to_s
  # => ["1", "2", "3"]

However the real strength in the library comes from allowing you to call methods with arguments:

[1,"2",3].select &X.is_a?(String)
  # => ["2"]

And, as everything in ruby is a method, create readable expressions without the noise of a one-argument block:

[{1 => 2}, {1 => 3}].map &X[1]
  # => [2, 3]

[1,2,3].map &-X
  # => [-1, -2, -3]

["a", "b", "c"].map &(X * 2)
  # => ["aa", "bb", "cc"]

[{}].each &X[1] = 2
  # => [{1 => 2}]

As an added bonus, the effect is transitive — you can chain method calls:

[1, 2, 3].map &X.to_f.to_s
  # => ["1.0", "2.0", "3.0"]

Gotchas

There are a few things to watch out for:

Firstly, &X can only appear on the left:

[1, 2, 3].map &(X + 1)
  # => [2, 3, 4]

[1, 2, 3].map &(1 + X) # WRONG
  # => TypeError, "coerce must return [x, y]"

[[1],[2]].map &X.concat([2])
  # => [[1, 2], [2, 2]]

[[1],[2]].map &[2].concat(X) # WRONG
  # => TypeError, "Metavariable#to_ary should return Array"

Secondly, other arguments or operands will only be evaluated once, and not every time:

i = 0
[1, 2].map &(X + (i += 1)) # WRONG
  # => [2, 3]

i = 0
[1, 2].map{ |x| x + (i += 1) }
  # => [2, 4]

Bugs

If you create an assigning callable (e.g. X[a] = b, X.a = b ) without an immediate preceding &, then b.class#to_proc will return the assigning callable the first time, and only the first time, you call it. If you want to get access to an assigning callable that you've defined using &X, you must do: lambda &X[a] = b instead.

Epilogue

For bug-fixes or enhancements, please contact the author: Conrad Irwin conrad.irwin@gmail.com

For an up-to-date version, try http://github.com/rapportive-oss/ampex

This library is copyrighted under the MIT license, see LICENSE.MIT for details.

Something went wrong with that request. Please try again.