0
0

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 1 year has passed since last update.

ruby returnの返り値が複数の場合

Posted at

はじめに

メソッド内の処理後、返り値が複数になる場合はどうなるのか気になったので調査し、検証してみました。

returnを使わない場合の返り値

test.rb
def return_test(value)
  sum_a = 5
  sum_b = 10
  sum_c = 15
  sum_a *= value
  sum_b *= value
  sum_c *= value
end

value = 10

x = return_test(value)

puts x

結果

=> 150

メソッドの最後の処理結果しか返ってこない

returnで返り値を複数指定した場合

test.rb
def return_test(value)
  sum_a = 5
  sum_b = 10
  sum_c = 15
  sum_a *= value
  sum_b *= value
  sum_c *= value
  return sum_a,sum_b,sum_c
end

value = 10

x = return_test(value)

puts x

結果

=> 50
=> 100
=> 150

return返り値を複数指定しても値が返ってくる

上記の例で言うとreturnに複数の式を指定すると変数xに配列の形で値が代入されているようで配列を指定してみるとreturnの後ろに記述した順番で配列が組まれていました。

test.rb
puts x[0] => 50
puts x[1] => 100
puts x[2] => 150

今後も疑問に思ったことを調査、検証してブログに書いていきます。

参考
https://docs.ruby-lang.org/ja/latest/doc/spec=2fcontrol.html#return

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?