LoginSignup
2
0

More than 3 years have passed since last update.

Rubyで2つの変数を入れ替える

Last updated at Posted at 2019-06-12

一時変数を使った(よくある方法)

一時変数(ここでは tmp )を用いて、値を入れ替える方法。

foo = 'foo'
bar = 'bar'

# 入れ替え作業
tmp = foo
foo = bar
bar = tmp

多重代入を使ったやり方

多重代入を使うと1行で複数の代入を行うことができます。
メリットとしては、一時変数が不要、3行→1行になるばかりでなく、入れ替える意図が明確になります。

foo = 'foo'
bar = 'bar'

# 入れ替え作業
foo, bar = bar, foo

# => [
#      [0] "bar",
#      [1] "foo"
#    ]

foo # => "bar"
bar # => "foo"
2
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
2
0