LoginSignup
0
0

More than 3 years have passed since last update.

今日のメモ(添字演算子、多重代入)

Posted at

添字演算子

添字には負の数値(-の値)を指定できる。
要素(a=[n1,n2,n3,n4])の末尾を-1とし、先頭に向かって順に減っていく。
スクリーンショット 2020-08-06 15.57.15.png
更に添字に2つの整数を指定すると複数の要素を出力できます。

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

多重代入

コード内の複数の変数に一度に代入をする。
メソッドの返り値で複数の値を返し、多重代入で受け取る事もできるがreturnを指定する必要がある。

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

変数よりも代入する値が少ない場合は、余った変数にnilが入る。

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

変数よりも代入する値が多い場合は、余った値は無視される。

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

1つの変数に複数の値を代入した場合は配列の代入と見なされるので注意ですが、値が余った場合最後の変数に*をつける事で配列としてまとめて代入されます。

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0