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.
This is another way to do this: use the Array#index method. It returns the index of the first occurrence of the element in the array. This returns the index of the first word in the array that contains the letter 'o'. index still iterates over the array, it just returns the value of the element.
The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.
This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).
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
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