How to create an array of objects in rails?

I need to know how to create an array of objects in rails and how to add elements to it.

I am new to rubies on rails, and this might be some kind of silly question, but I can't find the exact answer for that. So please give some expert ideas about this.

+6
source share
4 answers

Since all objects in Ruby (including numbers and strings), any array that you create is an array of objects that does not have restrictions on the types of objects that it can hold. There are no integer arrays or widget arrays 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.

+11
source

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 that you like, it should not be of a specific type.

+17
source

Depending on the situation, I like this design to initialize the array.

 # Create a new array of 10 new objects Array.new(10) { Object.new } #=> [#<Object:0x007fd2709e9310>, #<Object:0x007fd2709e92e8>, #<Object:0x007fd2709e92c0>, #<Object:0x007fd2709e9298>, #<Object:0x007fd2709e9270>, #<Object:0x007fd2709e9248>, #<Object:0x007fd2709e9220>, #<Object:0x007fd2709e91f8>, #<Object:0x007fd2709e91d0>, #<Object:0x007fd2709e91a8>] 
+2
source

Also, if you need to create an array of words, the following construction can be used to avoid the use of quotation marks:

 array = %w[first second third] 

or

 array = %w(first second third) 
0
source

Source: https://habr.com/ru/post/894165/


All Articles