1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

自分用rubyメモ 多重代入について(随時追記)

1
Last updated at Posted at 2016-06-14

多重代入で色々やってみる

multiple_assignment.rb
a,b,c = 1,2  # cにはnilが入る!
p [a,b,c]

a,b,c = 1,2,3,4  # *を付けていないので4は溢れる
p [a,b,c]

a,b,*c = 1,2,3,4  # cには余った数値が配列になって代入される!
p [a,b,c]

a,*b,c = 1,2,3,4  # bに余った数値が(以下同文)!
p [a,b,c]

a,b = 0,1
a,b = b,a  # 交換処理!
p [a,b]

ary = [1,[2,3],4]
a,b,c = ary
print a,b,c
puts

a,(b1,b2),c = ary
print [a,b1,b2,c]
result
[1, 2, nil]
[1, 2, 3]
[1, 2, [3, 4]]
[1, [2, 3], 4]
[1, 0]
1[2, 3]4
[1, 2, 3, 4]

結論

  • 交換処理wtmpを使わないなんて…
  • 変数に*を付けるとその変数は余った数値を配列として全部貰ってくる!
1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?