timpone
timpone

Reputation: 19929

take an array of attributes to make a hash of only those attributes

I have an Item class with many attributes but for this case lets say it has a name, detail, inventory_count, price on it. in These are all ruby primitives.

I would like to get back a hash of like 'name' and 'detail' such that:

vals=%[name detail]

item=Item.find(23)

# somethign like???

g={}
vals.map { |atr| g[atr]=item.??? }

or some other technique. How would I take a string representation and get the attribute of an instance? Is there an easier / better way to do this?

edit 1

looks like send might do it. Let me check

Upvotes: 0

Views: 873

Answers (1)

Rustam Gasanov
Rustam Gasanov

Reputation: 15781

#attributes returns an object in hash representation, #slice returns a hash containing only the given keys, so:

item.attributes.slice('name', 'detail')

Upvotes: 2

Related Questions