push in array with auto-create in ruby

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`

In a single line it will be as:

toto = (toto || [] ) << 'titi'

and for Person name:

toto = (toto || [] ) << person.name

If you don't need to rewrite the Array do as follows:

( toto ||= [] ) << 'titi'

In this case I'd just go straight to each_with_object:

toto = Person.all.each_with_object([]) do |person, toto|
  toto.push(person.name)
end

Alternatively, you could just map it:

toto = Person.all.map(&:name)

Tags:

Arrays

Ruby

Push