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 5 years have passed since last update.

[ruby] returnとは

0
Posted at

returnとは

定義したメソッドの中の戻り値を返す情報をあらわします

メソッドの中でreturnを書いた時点で、そのメソッドから抜け出してしまうという特徴があります

戻り値を返すには

戻り値を返したい情報の前にreturnと書くことです

コードでかいてみます


def hello
  return "こんにちは"
end

puts hello

# 実行結果
こんにちは
def hello
  return "こんにちは"

  "おはよう"
  
end

puts hello

# 実行結果
こんにちは

この場合returnの時点でメソッドから抜け出してしまうのでおはようは実行されません

def hello
  "こんにちは"

  "おはよう"

end

puts hello

# 実行結果
おはよう

この場合、returnがないので一番最後の式が評価されることとなるので

おはようが戻り値となります

まとめ

return は省略可
returnがある場合はそこでの戻り値でメソッドは抜けます
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?