























Ruby 2.7 deprecated the use of hashes in the last argument of a method call. Fix this warning by removing the curly braces or adding a hash splat (**) to a variable argument.
Ally Piechowski · · Updated · 2 min read
warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
warning: The called method `test' is defined here
Ruby 2.7 deprecated the use of hashes in the last argument of a method call.
Luckily, this can be resolved by removing the curly braces of a direct hash
argument, or adding a hash splat ** to a variable argument
For these examples, we’ll be using the following sample function to demonstrate the warnings:
def hello(name: 'World')
"Hello, #{name}!"
end
When a hash is the last argument in a method and the method expects keyword arguments, then Ruby automatically converts this argument into keyword arguments.
To remove the warning, we can simply remove the curly braces. This solution works for any number of keywords.
Likewise, when a hash is passed as a variable in the final argument slot, it is also converted into keyword arguments. Since this hash could be coming from elsewhere in the application, it isn’t always as easy as moving the hash into the method parameters and removing curly braces…
details = { name: 'Alex' }
hello(details)
Luckily, Ruby has a feature called a “hash splat” (**). When a hash splat is
applied on a hash, it expands the hash’s keys into multiple arguments, allowing
this error to be dissipated as the method receives keyword arguments rather
than receiving a hash.
details = { name: 'Alex' }
hello(**details)
If we want to suppress this warning, we can do this via an environment variable.
After executing export RUBYOPT='-W:no-deprecated', any Ruby command will
ignore deprecation notices. This sets an environment variable telling Ruby to
ignore deprecation notices.
If instead, you want to ignore notices per command, you must use the inline
environment variable syntax, RUBYOPT='-W:no-deprecated' ruby file.rb.
For instance, for a Rails app, you would use RUBYOPT='-W:no-deprecated' rails server
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。