Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

push in array with auto-create in ruby

Tags:

arrays

ruby

push

i want to know if it's possible to push in array with auto-creation of array if doesn't exist already, like in PHP:

$toto[] = 'titi';

if $toto is not already defined, it will create array and push 'titi' into. If already exist, it will just push.

in Ruby i have to do:

toto ||= []
toto.push('titi')

It's possible to do this in one line?

Because if i have an loop, it will test "||=" for nothing except the first time:

Person.all.each do |person|    
   toto ||= [] #with 1 billion of person, this line is useless 999 999 999 times...
   toto.push(person.name)

have you a better solution?

thx.

like image 429
Matrix Avatar asked Dec 13 '13 15:12

Matrix


People also ask

How do you push items into an array in Ruby?

The push() function in Ruby is used to push the given element at the end of the given array and returns the array itself with the pushed elements. Parameters: Elements : These are the elements which are to be added at the end of the given array. Returns: the array of pushed element.

What does << mean in Ruby?

In ruby '<<' operator is basically used for: Appending a value in the array (at last position) [2, 4, 6] << 8 It will give [2, 4, 6, 8] It also used for some active record operations in ruby.

Are arrays dynamic in Ruby?

Unlike other programming languages like Java, Ruby only has dynamic arrays but no static arrays.

What is concat Ruby?

concat is a String class method in Ruby which is used to Concatenates two objects of String. If the given object is an Integer, then it is considered a codepoint and converted to a character before concatenation. Parameters: This method can take the string object and normal string as the parameters.


1 Answers

toto = Person.all.reduce([]) do |arr, person|
  arr << person.name
end

or you could simply pluck the names if they come from the DB

toto = Person.pluck(:name) # SELECT `people.name` FROM `people`
like image 154
Kyle Avatar answered Sep 21 '22 11:09

Kyle