Skip to content

Instantly share code, notes, and snippets.

@leshill
Forked from croaky/dynamic_mapper.rb
Created June 21, 2010 22:57
Show Gist options
  • Save leshill/447665 to your computer and use it in GitHub Desktop.
Save leshill/447665 to your computer and use it in GitHub Desktop.
class Array
def method_missing(method, *args, &block)
if key_value = dynamic_mapper?(method)
map_dynamically(key_value[1], key_value[2])
else
super
end
end
def dynamic_mapper?(method)
/^map_([_a-zA-Z]\w*)_to_([_a-zA-Z]\w*)$/.match(method.to_s)
end
def map_dynamically(key, value)
inject({}) do |result, hash|
result.update(hash[key] => hash[value])
end
end
end
project_hashes = [{'name' => 'suspenders', 'color' => 'green'}, {'name' => 'shoulda', 'color' => 'green'}]
puts project_hashes.map_name_to_color.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment