Skip to content

Instantly share code, notes, and snippets.

@ebababi
Created March 27, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebababi/70ee124c24deb9ebbc2b to your computer and use it in GitHub Desktop.
Save ebababi/70ee124c24deb9ebbc2b to your computer and use it in GitHub Desktop.
Ruby core extension for Array#find_value which compares each entry in enum with value or passes to block and returns the value for the first for which the evaluated value is non-false.
class Array
# Compares each entry in enum with value or passes to block. Returns the value
# for the first for which the evaluated value is non-false. If no object
# matches, returns the default value or nil.
#
# If neither block nor argument is given, an enumerator is returned instead.
#
# find_value(value, default = nil) → obj or default
# find_value(default = nil) { |obj| block } → obj or default
# find_value → an_enumerator
def find_value(*args, &block)
return find_index if args.empty? unless block_given?
if block_given?
fail ArgumentError, "wrong number of arguments (#{args.size} for 0..1)" unless (0..1).include? args.size
default = args.pop
index = find_index &block
else
fail ArgumentError, "wrong number of arguments (#{args.size} for 1..2)" unless (1..2).include? args.size
default = args.size == 2 ? args.pop : nil
index = find_index args.pop
end
return default unless index
fetch index
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment