LoginSignup
0
0

More than 3 years have passed since last update.

Rubyでreturnを省略する際に気をつけること

Posted at

返却前の処理に気をつけると良い。

example

例えば、以下のようなメソッドを実装する場合、


p sample_method()
# => { 'hoge' => 0, 'piyo' => 0 }

返却前の処理を誤って記述してしまうと、returnを利用する場合は構文エラーを出してくれるが、


def sample_method
  result = { 'hoge' => 0 }

  # 1の後に間違ってカンマ","をつけてしまった
  result['piyo'] = 1,
  return result
end

# =>
# SyntaxError (xxx:nn: void value expression)
#   return result
#   ^~~~~~
# xxx:nn: syntax error, unexpected local variable or method, expecting `end'
#   return result
#          ^~~~~~

returnを省略する場合は意図しない値が返ってきてしまう場合がある。


def sample_method
  result = { 'hoge' => 0 }

  # 1の後に間違ってカンマ","をつけてしまった
  result['piyo'] = 1,
  result
end

p sample_method()
# => [1, {"hoge"=>0, "piyo"=>[...]}]

Rubyとしては正しい構文であるため、エラーは発生しない。

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