1

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

1 Answer 1

2

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

item.attributes.slice('name', 'detail') 
Sign up to request clarification or add additional context in comments.

2 Comments

cool - how would I pass an array of desired attributes into slice()?
@timpone just unpack array like this: item.attributes.slice(*array)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.