Created
April 9, 2015 12:46
-
-
Save am-kantox/e9f66b73d115af4a64e2 to your computer and use it in GitHub Desktop.
Sensible Arrays
This file contains 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
module Sensible | |
module Array | |
class ::Array | |
alias_method :select_std, :select | |
def select arg = nil, &cb | |
preselected = case arg | |
# no argument ⇒ standard processing | |
when NilClass then self | |
# strings are matched as is | |
when String then select_std do |e| | |
e.is_a?(String) && e =~ Regexp.new(Regexp.escape(arg)) | |
end | |
# return only same and derived classes | |
when Class then select_std do |e| | |
e < arg | |
end | |
# inclusive deep recurse | |
when Array then arg.inject([]) do |memo, e| | |
memo + select(e) | |
end.uniq | |
# for any other use `=~` operator | |
else select_std do |e| | |
begin | |
e.respond_to?(:to_s) && e.to_s =~ arg | |
rescue TypeError => e | |
false | |
end | |
end | |
end | |
block_given? ? preselected.send(:select_std, &cb) : preselected | |
end | |
private :select_std | |
def to_proc | |
lambda do |item| | |
case item | |
when Hash then item.select { |k, _| self.include? k } | |
when Class | |
map do |i| | |
if i.respond_to?(:to_sym) | |
is = i.to_sym | |
[ | |
item.singleton_methods.include?(is) ? item.singleton_method(is) : nil, | |
item.instance_methods.include?(is) ? item.instance_method(is) : nil | |
] | |
else | |
[nil, nil] | |
end | |
end | |
when lambda do |it| | |
count do |i| | |
i.respond_to?(:to_sym) && it.respond_to?(i.to_sym) | |
end == length # > 0 might be an option | |
end then map { |m| item.send(m) } | |
else item.send(*self) | |
end | |
end | |
end | |
end | |
end | |
end |
Author
am-kantox
commented
Apr 9, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment