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

【初学者向け】return(返り値)のイメージを掴もう!

Posted at

はじめに

初学者向けに書いています。
簡単に返り値の基礎と心がけるべき点を書きました。

return(返り値)について

返り値は読んで字の如く、メソッドを呼び出した箇所へ返す値である。
"返す"という表現で理解し難い場合は"置き換わる"とイメージした方がわかりやすいかもしれない。
(あくまでイメージ)

def method
  "あ"
  "い"
  return "う"
  "え"
  "お"
end

puts method
実行結果

Rubyではreturnは書かなくてもOKで、書かなかった場合はメソッドの最後の行がreturnされる。

def method
  "あ"
  "い"
  "う"
  "え"
  "お"
end

puts method
実行結果

意識して欲しいこと

メソッドではこの返り値が大事で、ちゃんと自分の欲しいものを返さないとどれだけ処理を書こうが台無しになる。

def multi(number)
  number + number
  number * number
  "こんにちは"
end

puts "methodの返り値は『#{method(10)}』です。"
出力結果
methodの返り値はこんにちはです

上記の例は露骨ではあるが、初学者はメソッドをモリモリ書いているうちに何が欲しくてメソッドを書いているか見失うことは良くあることです。
したがってメソッドを描くときは**何が欲しいか(返り値は何か)**を意識して書きましょう!

最後に

「ここが分かりにくかった」「これは何?」などの質問や、レイアウト等の書き方にアドバイスがある方はお気軽に(優しく)コメントを頂けると助かります。

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