简体   繁体   English

在 Ruby 中将哈希作为参数传递

[英]Passing a hash as arguments in Ruby

I have the following code:我有以下代码:

user = User.from_google(from_google_params)

  def from_google_params
    @from_google_params ||= {
      uid: auth.uid,
      email: auth.info.email,
      full_name: auth.info.name,
      avatar_url: auth.info.image
    }
  end

...and here is the from_google method the hash is being passed to. ...这里是散列传递到的 from_google 方法。

def self.from_google(email:, full_name:, uid:, avatar_url:)

When I run this I am getting an argument error ArgumentError (wrong number of arguments (given 1, expected 0; required keywords: email, full_name, uid, avatar_url)):当我运行它时,我收到一个参数错误ArgumentError (wrong number of arguments (given 1, expected 0; required keywords: email, full_name, uid, avatar_url)):

Here is what I see in the console:这是我在控制台中看到的:

>> from_google_params.inspect
=> "{:uid=>\"100373362533979950619\", :email=>\"marklocklear@extension.org\", :full_name=>\"Mark Locklear\", :avatar_url=>\"https://lh3.googleusercontent.com/a-/AOh14Gh1leKarrW8SCvxxwvaAcDkAISXYQ38k4xPQuC1Rg=s96-c\"}"
>> from_google_params.class
=> Hash

How can I make this work?我怎样才能使这项工作?

Use the double splat operator (**) to convert the hash into keyword arguments.使用双 splat 运算符 (**) 将哈希转换为关键字参数。

user = User.from_google(**from_google_params)

The separation of keywords and positional arguments was a big change in Ruby 3. Previous versions of Ruby would coerce the last positional argument into keywords if its a hash - this behavior was depreciated in Ruby 2.7 and removed completely in 3.0. 关键字和位置参数分离在 Ruby 3 中是一个很大的变化。以前版本的 Ruby 会将最后一个位置参数强制转换为关键字,如果它是一个散列 - 这种行为在 Ruby 2.7 中被弃用,并在 3.0 中完全删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM