Created
June 14, 2013 21:39
-
-
Save spalladino/5785524 to your computer and use it in GitHub Desktop.
Array#first redefinition so it can accept a block and behave like find, for compatibility with .NET LINQ programmers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Array | |
| def first_with_block(&block) | |
| block_given? ? find(&block) : first_without_block | |
| end | |
| alias_method_chain :first, :block | |
| end | |
| # 1.9.3p0 :009 > [1,2,3,4,5].first{|x| x > 2} | |
| # => 3 | |
| # 1.9.3p0 :010 > [1,2,3,4,5].first | |
| # => 1 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Works only in Rails (due to alias_method_chain)