Bfca16459c82a7836c3d5c8d79f0b640

Is there a shorter version, or do I always have to code the block syntax? Something like @documents.collect_call(:to_hash)? Btw. It's Rails so maybe there might be something in ActiveSupport.

@public_documents = @documents.map { |document| document.to_hash }

Refactorings

No refactoring yet !

A8d3f35baafdaea851914b17dae9e1fc

Adam

September 8, 2009, September 08, 2009 16:26, permalink

1 rating. Login to rate!

There is, in fact, something in ActiveSupport.

@documents.map(&:to_hash)
F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

September 8, 2009, September 08, 2009 16:40, permalink

No rating. Login to rate!

&:foo calls #to_proc on an object, as Adam shows. so &:to_hash becomes:

{ |obj| obj.to_hash }
F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

September 8, 2009, September 08, 2009 16:41, permalink

No rating. Login to rate!

Note that you can use & as an unary 'method' for any object, however it seems that most people just use it with symbols.

F30b04ed4d0b3fc4bc791a28815f34ca

ReinH

September 9, 2009, September 09, 2009 17:54, permalink

No rating. Login to rate!

& is not a unary method. It's a sigil that instructs the interpreter to treat the following variable as a block, similar to the * sigil for array expansion.

Your refactoring





Format Copy from initial code

or Cancel