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.
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.
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.
Unlike other programming languages like Java, Ruby only has dynamic arrays but no static arrays.
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.
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`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With