Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can multiple objects be inserted with the << operator in Rails 3.1?

Could I write the following ...

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

As the following instead? ...

      obj.categories << raw_data.categories
like image 964
Jacob Avatar asked Nov 28 '11 21:11

Jacob


People also ask

What does << mean in rails?

It means add to the end (append).

What is << operator in Ruby?

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.


1 Answers

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"]
like image 183
BM5k Avatar answered Sep 28 '22 09:09

BM5k