I have the following:
foo ||= []
foo << "bar"
And I am sure this can be done in one line, I just cannot find how.
Important is, that foo may, or may not exist. If it exists it is always an Array, if it does not exist, it must become an array and get a variable appended to it.
3 Answers
Like this:
(foo ||= []) << "bar"
The parenthesized bit returns foo if it already exists, or creates it if it doesn't, and then the << appends to it.
If you only want to add "bar" when foo is not already defined:
foo ||= ["bar"]
if you want to add "bar" regardless of whether or not foo already exists:
(defined? foo) ? foo << "bar" : foo = ["bar"]
However, in the latter case, I personally prefer the way the original code is written. Sure it can be done in one line, but I think the two line implementation is more readable.
What code are you writing where you're unsure if a local variable exists?
If it's something like
def procedural_method(array)
result ||= []
array.each do |array_item|
result << bar(array_item)
end
result
end
then you could try a more functional programming approach
def functional_programming_method(array)
array.map do |array_item|
bar(array_item)
end
end