Skip to content

Instantly share code, notes, and snippets.

@sandro
Forked from leshill/dynamic_mapper.rb
Created June 22, 2010 01:57
Show Gist options
  • Save sandro/447818 to your computer and use it in GitHub Desktop.
Save sandro/447818 to your computer and use it in GitHub Desktop.
class Array
DYNAMIC_MAPPER_REGEXP = /^map_([_a-zA-Z]\w*)_to_([_a-zA-Z]\w*)$/
def method_missing(method, *args, &block)
dynamic_mapper?(method) do |match|
map_dynamically(match[1], match[2])
end || super
end
def dynamic_mapper?(method)
yield Regexp.last_match if method.to_s =~ DYNAMIC_MAPPER_REGEXP
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