As someone who came from Java background and being a newbie to Ruby, I was wondering if there is a simple way of doing this with ruby.
new_values = foo(bar)
if new_values
if arr
arr << new_values
else
arr = new_values
end
end
Assuming "arr" is either an array or nil, I would use:
arr ||= []
arr << new_values
If you're doing this in a loop or some such, there might be more idiomatic ways to do it. For example, if you're iterating a list, passing each value to foo()
, and constructing an array of results, you could just use:
arr = bars.map {|bar| foo(bar) }
If I'm understanding you correctly, I would probably do:
# Start with an empty array if it hasn't already been set
@arr ||= []
# Add the values to the array as elements
@arr.concat foo(bar)
If you use @arr << values
you are adding the entire array of values to the end of the array as a single nested entry.
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