Skip to content

Instantly share code, notes, and snippets.

@spalladino
Created June 14, 2013 21:39
Show Gist options
  • Select an option

  • Save spalladino/5785524 to your computer and use it in GitHub Desktop.

Select an option

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
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
@spalladino
Copy link
Author

Works only in Rails (due to alias_method_chain)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment