# Creating array of hashes

**URL:** <https://www.ruby-forum.com/t/creating-array-of-hashes/196851>\
**Category:** Rails\
**Created:** [November 27, 2008, 11:29am UTC](https://www.ruby-forum.com/t/creating-array-of-hashes/196851 "2008-11-27T11:29:27Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hema\_mca](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/779978/32.png) [@hema\_mca](https://www.ruby-forum.com/u/hema_mca)\
**Post date:** [November 27, 2008, 11:29am UTC](https://www.ruby-forum.com/t/creating-array-of-hashes/196851/1 "2008-11-27T11:29:27Z")

</div>

I have a problem,

please check the code

Fields = Array.new  
Fields [0] = “sno”  
Fields [1] = “username”  
Fields [2] = “designation”  
Fields [3] = “salary”  
Fields [4] = “dob”  
Fields [5] = “email”  
Fields [6] = “doj”

These are the fields of the object ‘Employee’

The Employees array contains of the set of employee objects…

I need to have the array of hashes as  
[{employee\_record1},{employee\_record2}… n records]

For this i tried as the…

result = []

for employee in Employees  
res = {}  
for field in fields  
res \<\< { field =\> employee.send(field)}  
end  
result \<\< res  
end  
But it is not working…

Finally i have to replace the ‘result’ with the PDF::SimpleTable.data  
through the statement

=\> table.data.replace result

which accepts only the hashes… whose columns are the keys and the  
column  
data as values

Please Help me Thank You

---

<div class="post-metadata">

**Author:** ![hema\_mca](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/779978/32.png) [@hema\_mca](https://www.ruby-forum.com/u/hema_mca)\
**Post date:** [November 27, 2008, 12:53pm UTC](https://www.ruby-forum.com/t/creating-array-of-hashes/196851/2 "2008-11-27T12:53:47Z")

</div>

Hi - see below…

hema gonaboina wrote:  
…

> ```
> for field in fields
> 
> ```

You used ‘Fields’ above instead of ‘fields’ here.

> ```
> res << { field => employee.send(field)}
> 
> ```

res[field] = employee.send(field)

‘res’ is a hash. You build it by setting key/value pairs not pushing  
onto a sequential array.  
That should probably do it.

Some other things that might be of interest:  
employee.attributes  
will give you a hash of all the fields and their values for an  
employee object but you might only be wanting a subset. (You could  
‘delete’ them.)  
Employee.column\_names  
will give you an array of all the column names.

> which accepts only the hashes… whose columns are the keys and the column  
> data as values
> 
> Please Help me Thank You

–  
Daniel B.
