Skip to content

Commit

Permalink
improved pluck method in Mojo::Collection to be able to extract value…
Browse files Browse the repository at this point in the history
…s from hash references
  • Loading branch information
kraih committed Oct 6, 2014
1 parent 44844d9 commit 52eb3e3
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 6 deletions.
4 changes: 3 additions & 1 deletion Changes
@@ -1,6 +1,8 @@

5.48 2014-10-06
5.48 2014-10-07
- Added from_json and to_json functions to Mojo::JSON.
- Improved pluck method in Mojo::Collection to be able to extract values
from hash references.

5.47 2014-09-28
- Improved url_for performance.
Expand Down
12 changes: 7 additions & 5 deletions lib/Mojo/Collection.pm
Expand Up @@ -69,8 +69,8 @@ sub new {
}

sub pluck {
my ($self, $method, @args) = @_;
return $self->new(map { $_->$method(@args) } @$self);
my ($self, $key) = (shift, shift);
return $self->new(map { ref eq 'HASH' ? $_->{$key} : $_->$key(@_) } @$self);
}

sub reduce {
Expand Down Expand Up @@ -262,13 +262,15 @@ Construct a new array-based L<Mojo::Collection> object.
=head2 pluck
my $new = $collection->pluck($key);
my $new = $collection->pluck($method);
my $new = $collection->pluck($method, @args);
Call method on each element in collection and create a new collection from the
results.
Extract hash reference value or call method on each element in collection and
create a new collection from the results.
# Equal to but more convenient than
# Longer version
my $new = $collection->map(sub { $_->{$key} });
my $new = $collection->map(sub { $_->$method(@args) });
=head2 reduce
Expand Down
2 changes: 2 additions & 0 deletions t/mojo/collection.t
Expand Up @@ -144,6 +144,8 @@ is_deeply [$collection->slice(6, 1, 4)->each], [7, 2, 5], 'right result';
is_deeply [$collection->slice(6 .. 9)->each], [7, 10, 9, 8], 'right result';

# pluck
is c({foo => 'bar'}, {foo => 'baz'})->pluck('foo')->join, 'barbaz',
'right result';
$collection = c(c(1, 2, 3), c(4, 5, 6), c(7, 8, 9));
is $collection->pluck('reverse'), "3\n2\n1\n6\n5\n4\n9\n8\n7", 'right result';
is $collection->pluck(join => '-'), "1-2-3\n4-5-6\n7-8-9", 'right result';
Expand Down

0 comments on commit 52eb3e3

Please sign in to comment.