What does the comma mean for the equal sign in Ruby?

In some code, Ruby saw something like this:

def getis;gets.split.map(&:to_i);end k,=getis # What is this line doing? di=Array::new(k){Array::new(k)} 
+6
source share
2 answers

It assigns the first element of an array using Ruby's multiple assignment :

 a, = [1, 2, 3] a #=> 1 

Or:

 a, b = [1, 2, 3] a #=> 1 b #=> 2 

You can use * to extract the rest of the elements:

 a, *b = [1, 2, 3] a #=> 1 b #=> [2, 3] 

Or:

 *a, b = [1, 2, 3] a #=> [1, 2] b #=> 3 
+12
source

It works like that. If lhs has one element and rhs has several values, then lhs gets the assigned array of values, for example this.

 a = 1,2,3 #=> a = [1,2,3] 

If lhs has more elements than rhs , then excess elements in lhs discarded

 a,b,c = 1,2 #=> a = 1, b = 2, c = nil 

therefore

a, = 1,2,3 #=> a = 1 . The rest, that is, [2,3], are discarded

+6
source

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


All Articles