0.0
No commit activity in last 3 years
No release in over 3 years
Finds the first element for which the block returns non-falsy and returns the value.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 1.3
>= 0
>= 0
~> 2.13
 Project Readme

Find and Map

Anthony M. Cook (2013)

Finds and returns the value of the block.

Gem Version Build Status Code Climate Dependency Status

Usage

Put it in your Gemfile:

gem 'find_and_map'

Then you can include it on your own Enumerable object:

include FindAndMap

Or you can use the core extension directly the Gemfile:

gem 'find_and_map', require: 'find_and_map/core_ext'

Then you can use it like this:

{a: 1, b: 2}.find_and_map do |key, value|
  value if key == :a
end #=> 1

Background

I was looking for a way to simply find the first matching element in an enumerable and return a mapped result.

Using the same block above (in the Usage section) find returns [:a, 1] and map returns [1, nil]. But I want just the value, or even some other object based on it, but only that and nothing else.

This method finds the first match (like Enumerable#find) and then return the result of the block rather than the matching element (like Enumerable#map).

I don't like doing explict returns in the middle of loops, or nil checks if find fails, explicit breaks that alter the functionality of a standard iterator, and using compact after a map just seems excessive.

Here's some alternative ways of getting the desired result that violate the above constraints...

Using find:

{a: 1, b: 2}.find do |key, value|
  break value if key == :a
end

Using map:

{a: 1, b: 2}.map do |key, value|
  value if key == :a
end.compact

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request