Question

Could I write the following ...

      raw_data.categories.each do |category|
          obj.categories << category
      end

As the following instead? ...

      obj.categories << raw_data.categories
Was it helpful?

Solution

obj.categories |= raw_data.categories 

OTHER TIPS

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"]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top