Could I write the following ...
raw_data.categories.each do |category|
obj.categories << category
end
As the following instead? ...
obj.categories << raw_data.categories
It means add to the end (append).
As a general convention, << in Ruby means "append", i.e. it appends its argument to its receiver and then returns the receiver. So, for Array it appends the argument to the array, for String it performs string concatenation, for Set it adds the argument to the set, for IO it writes to the file descriptor, and so on.
Take a look at Array#<<
and Array#push
.
Array#<<
takes one which is appended in place to given array. For example:
irb> array = %w[ a b c ] # => ["a", "b", "c"]
irb> array << 'd' # => ["a", "b", "c", "d"]
however, if you pass an array, you'll be surprised at the result
irb> array << ['e', 'f', 'g'] # => ["a", "b", "c", "d", ["e", "f", "g"]]
Array#push
can handle 1+ objects, each of which are appended to the array.
irb> array = %w[ a b c ] # => ["a", "b", "c"]
irb> array.push 'd' # => ["a", "b", "c", "d"]
However, calling #push
with an array gives you the same result as #<<
.
irb> array.push ['e', 'f', 'g'] # => ["a", "b", "c", "d", ["e", "f", "g"]]
In order to push all of the elements in the array, just add a *
before the second array.
irb> array.push *['e', 'f', 'g'] # => ["a", "b", "c", "d", "e", "f", "g"]
On a related note, while Array#+
does concatenate the arrays, it will also allow duplicate values.
irb> array = %w[ a b c ] # => ["a", "b", "c"]
irb> array += ['d'] # => ["a", "b", "c", "d"]
irb> array += ['d'] # => ["a", "b", "c", "d", "d"]
If this is undesired, the |
operator will return a union of two arrays, without duplicate values.
irb> array = %w[ a b c ] # => ["a", "b", "c"]
irb> array |= ['d'] # => ["a", "b", "c", "d"]
irb> array |= ['d'] # => ["a", "b", "c", "d"]
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