How to call a method with named parameters using a hash

Asked

Viewed 883 times

-1

I wonder if you have how to pass parameters to a parameter method named via hash. It has to pass the parameters that remain for another function as in the following example?

params = {key: "value",key2: "value2"}
def func(key1: nil, key2: nil, **args)
    other_func **args
    ...
end
func params

Occurrence of the Rails problem:

#No controle
@session = SessionUser.new(params[:session_user].merge(session: session))

# classe SessionUser
def initialize(session: nil, email: nil, password: nil, **args)
    @session = session
    @email = email
    @password = password
end
  • 1

    Your example works.

  • It says that the number of arguments is wrong, it certainly considers the hash as a parameter only and if it were via array (*args) it would work, but this is not what I need

  • The syntax of hash ** is only valid from version 2.0 Ruby. Before that you should use a hash parameter explicitly.

  • My version is 2.1.5, added below the occurrence of the problem to help

1 answer

0

  • Take a look at this method of ActiveSupport http://apidock.com/rails/Hash/symbolize_keys

Browser other questions tagged

You are not signed in. Login or sign up in order to post.