rubyist
rubyist

Reputation: 3132

how to delete an object's attribute from ruby array

I have a students array like this

[#<Student id: 2, admission_no: "2", gender: "m", blood_group: "A">,#<Student id: 3, admission_no: "3", gender: "m", blood_group: "A">]

I am getting this array via named_scope .... So is there any way to select only required attributes with named scope... I need to delete admission_no and blood_group from this and return an array only with students id and gender.. How is it possible. Iam using rails2.3

Upvotes: 0

Views: 1161

Answers (3)

kirti
kirti

Reputation: 33

do this Student.select('id, gender').find(:all)

Upvotes: 0

PythonDev
PythonDev

Reputation: 4317

named_scope_result.select('id, gender') will give you your desired result.

Upvotes: 1

Miotsu
Miotsu

Reputation: 1776

You want to have an array of hashes containing only the required fields, starting from your array.

Student.select('id, gender').find(:all)

will do if you want to consider all the Student objects in your database.

Starting from a generic Student array: students, you can achieve what you want by:

result = Array.new
students.each |s| do
  data = { "id" => s.id, "gender" => s.gender }
  result << data
end

Upvotes: 0

Related Questions