What does "<<" exactly in ruby ​​do?

I'm new to Ruby, so I'm still learning a few things. But I have good experience with Java and C.

I would like to know what exactly this does:

 [ 'a','b', 'c' ].each_with_index {|item, index| result << [item, index] } 

In particular, I'm interested in << . Some studies tell me that it is used to offset bits, but it is obvious that this is not the case here, so what is it doing here?

+4
source share
4 answers

The << operator adds elements to the result array in this case.

See " how to add elements to a Ruby array (solved) .

+12
source

This is the operator for adding an array .

<< is a method and will do different things for different classes. The array uses it to push the object to the end of the array. Fixnums use it for transfer .

+6
source

In Ruby, all things that are operators in C / Java, such as +, -, *, /, etc., are actually method calls. You can redefine them as you wish.

 class MyInteger def +(other) 42 # or anything you want end end 

Array defines a << method to denote "push this element at the end of this array." For integers, it is defined to shift bits.

In addition to Array, many other classes define << to represent any kind of "add" operation.

+6
source

This is basically an add statement.

It was used to add either an element to an array or a substring to a string

For arrays

1.9.2-p290: 009> arr = [1,2,3,4,5]

 => [1, 2, 3, 4, 5] 

1.9,2-p290: 010> arr <6

 => [1, 2, 3, 4, 5, 6] 

1.9.2-p290: 011>

For strings

1.9.2-p290: 011> str = "ruby"

 => "ruby" 

1.9.2-p290: 012> str <'Rails'

 => "rubyrails" 

1.9.2-p290: 013>

+4
source

Source: https://habr.com/ru/post/1395492/


All Articles