Skip to content

Instantly share code, notes, and snippets.

@JeffCohen
Created March 8, 2012 03:14
Show Gist options
  • Save JeffCohen/1998347 to your computer and use it in GitHub Desktop.
Save JeffCohen/1998347 to your computer and use it in GitHub Desktop.
Fun with array mapping
class Array
def method_missing(m, *args)
map_elements(m, args) || super
end
def map_elements(m, *args)
target_method = singular_of(m)
new_array = map do |element|
if element.respond_to?(target_method)
if args.length > 0
element.send(target_method)
else
element.send(target_method, args)
end
else
nil
end
end
return nil if new_array.compact.empty?
new_array
end
def singular_of(m)
begin
# Hope that Rails is installed
m.to_s.singularize
rescue
# Poor man's attempt to singularize
if m.to_s =~ /s$/
m = m.to_s[0..-2]
end
m
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment