Today's memo (subscript operator, multiple assignment)

Subscript operator

Negative numbers (-values) can be specified for the subscript. The end of the element (a = [n1, n2, n3, n4]) is set to -1, and it decreases in order toward the beginning. スクリーンショット 2020-08-06 15.57.15.png Furthermore, if you specify two integers for the subscript, you can output multiple elements.

a = [0,1,2,3,4,5]
a[1,3]
#=> [1,2,3]

Multiple assignment

Assign to multiple variables in your code at once. It is possible to return multiple values as the return value of the method and receive it by multiple assignment, but it is necessary to specify return.

def foo
    return 1,2,3
end
a,b,c = foo
p a
p b
p c
#=> 1
    2
    3

If there are fewer values to assign than variables, nil will be included in the surplus variables.

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

If there are more values to assign than variables, the extra values are ignored.

a,b = 1,2,3
p a
p b
#=> 1
    2

Note that if multiple values are assigned to one variable, it will be regarded as an array assignment, but if there are surplus values, they will be assigned together as an array by adding * to the last variable.

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

Recommended Posts

Today's memo (subscript operator, multiple assignment)
Assignment to multiple variables with the ternary operator
Swift's assignment operator returns tuples
Java learning memo (logical operator)