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?

Rubyの暗黙的な返り値を理解する

Last updated at Posted at 2025-02-08

1 はじめに

初学者が暗黙的な返り値というのを理解していないがためにエラーが起こってので備忘録として記載する。

2 そもそも返り値とは

「返り値とは、メソッドの実行結果として返される値のこと」
多くのプログラミング言語では、return文を使って明示的に返り値を指定する。
一方Rubyの場合、明示的なreturn文を使用しなくても、メソッド内で最後に評価された式の値が自動的に返り値となる。

3 Rubyの暗黙的な返り値とは

Rubyでは、メソッド内でーー最後に評価された式の値ーーが自動的にそのメソッドの返り値となるものである。
明示的なreturn文を使用しなくても、メソッドは値を返すものである、便利ですね。

明示的な返り値の具体例

def add(a, b)
return a + b
end

result = add(3, 4)
puts "3 + 4 = #{result}" # 出力: 3 + 4 = 7

暗黙的な返り値の例

def multiply(a, b)
a * b # この行が返り値となる
end

result = multiply(3, 4)
puts "3 * 4 = #{result}" # 出力: 3 * 4 = 12

4 じゃあ返らない場合はあるのかい?

ありまーす

関数に何も入れないと:

def no_return
end
puts no_return # 出力: nil

putsの場合はそもそも、、:

result = puts "Hello, World!"
puts result # 出力: nil

5 ようやく本題、私がやらかした愚かなミス

def calculate_and_print(a, b)
result = a * b
puts "計算結果: #{result}"
end

final_result = calculate_and_print(3, 4)
puts "最終結果: #{final_result}"

resultが当然出力されると思っていたのだが

出力結果

計算結果: 12
最終結果:

最後に評価される式がputs文であること、これが問題である。最終行のputsメソッドの返り値はputsの戻り値であるnilである。
そのため、final_resultにはnilが代入され、最終結果が空白になってしまった。

6 解決方法

def calculate_and_print(a, b)
result = a * b
puts "計算結果: #{result}"
result # この行が関数の返り値となる
end

final_result = calculate_and_print(3, 4)
puts "最終結果: #{final_result}"

出力結果

計算結果: 12
最終結果: 12

よくできました、頑張りましょう

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