Leon
Leon

Reputation: 1292

Remove unwanted attributes from an object in ruby

I have an object that has all the properties from the db from the call lets say:

u = User.find_by_email("[email protected]")

u has first_name, last_name, email, phone etc.

How can I get all attributes except first_name and last_name from the object itself, not by modifying the call to the model?

Upvotes: 11

Views: 19451

Answers (3)

Anderson Marques
Anderson Marques

Reputation: 898

Just call the delete method on the object.

Example:

2.3.3 :001 > my_obj = { "name" => "name", "surname" => "surname" }
2.3.3 :002 > my_obj.delete("surname")
2.3.3 :003 > my_obj
=> {"name"=>"name"}

Upvotes: 3

AJcodez
AJcodez

Reputation: 34186

It's probably more future-proof to select the attributes you do want:

u.attributes.slice('email', 'phone')

Upvotes: 6

Zippie
Zippie

Reputation: 6088

u.attributes.except("first_name", "last_name")

Upvotes: 30

Related Questions