Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create object array in rails?

I need to know how to create object array in rails and how to add elements in to that.

I'm new to ruby on rails and this could be some sort of silly question but I can't find exact answer for that. So can please give some expert ideas about this

like image 825
Coder Avatar asked Aug 03 '11 07:08

Coder


2 Answers

All you need is an array:

objArray = []
# or, if you want to be verbose
objArray = Array.new

To push, push or use <<:

objArray.push 17
>>> [17]

objArray << 4
>>> [17, 4]

You can use any object you like, it doesn't have to be of a particular type.

like image 61
Daniel Lyons Avatar answered Sep 19 '22 00:09

Daniel Lyons


Since everything is an object in Ruby (including numbers and strings) any array you create is an object array that has no limits on the types of objects it can hold. There are no arrays of integers, or arrays of widgets in Ruby. Arrays are just arrays.

my_array = [24, :a_symbol, 'a string', Object.new, [1,2,3]]

As you can see, an array can contain anything, even another array.

like image 45
edgerunner Avatar answered Sep 19 '22 00:09

edgerunner