Be careful when omitting return in Ruby

You should be careful about the processing before returning.

example

For example, when implementing the following method


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

If you mistakenly describe the process before return, a syntax error will occur when using return, but


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

  #Wrong comma after 1","I have attached
  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
#          ^~~~~~

If return is omitted, an unintended value may be returned.


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

  #Wrong comma after 1","I have attached
  result['piyo'] = 1,
  result
end

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

The syntax is correct for Ruby, so no error occurs.

Recommended Posts

Be careful when omitting return in Ruby
Do not return when memoizing in Ruby
Encoding when getting in Windows + Ruby
Be careful when using multiple articles
Be careful when using rails_semantic_logger with unicorn
[Ruby] Basic key to be strong in refactoring
Escape processing when creating a URL in Ruby
Behavior when wild card (**) is specified in ruby
Be careful if you find SHIFT-JIS in Java
Be careful when setting the class name when creating a document-based app in Swift
Class in Ruby
Heavy in Ruby! ??
Be absolutely careful when putting the result of and / or in a variable!
Be careful with requests and responses when using the Serverless Framework in Java
Correspondence when Ruby version does not switch in rbenv
Be careful about Ruby method calls and variable references
In Ruby, methods with? Do not always return true/false.
About eval in Ruby
Output triangle in Ruby
Variable type in ruby
Ruby Learning # 16 Return Statement
Fast popcount in Ruby
Be careful of initialization timing when using MessageEncryptor with Rails 5.2 / 6.0
Things to be aware of when writing code in Java
[Rails] Where to be careful in the description of validation
Object-oriented design that can be used when you want to return a response in form format