Skip to content

MR10b Metaprogramming Lab Solution

Dave Strus edited this page Jan 31, 2016 · 1 revision

SOLUTION: Metaprogramming

Mutant#attributes

To do that, we'll need to create a hash, loop through ATTRIBUTE_NAMES, adding a new key/value pair to the hash on each loop, and return the resulting hash.

def attributes
  attribute_collection = {}
  ATTRIBUTE_NAMES.each do |attribute_name|
    attribute_collection[attribute_name] = # wat?
  end
  attribute_collection
end

It's easy enough to create the hash and assign the keys, but how we get the value we want to assign each time through, given only the attribute name?

We'll need to use send again, but we're doing it from inside the object we need to send to this time.

def attributes
  attribute_collection = {}
  ATTRIBUTE_NAMES.each do |attribute_name|
    attribute_collection[attribute_name] = send(attribute_name)
  end
  attribute_collection
end

Stick a binding.pry somewhere in your application and give it a shot.

The functionality is all neatly and logically encapsulated into short methods in small classes, but it's still tough to navigate the code in our project since it's all in one big file. Let's do something about that.