【问题标题】:How can Ruby functions with named arguments get called with a hash instead?带有命名参数的 Ruby 函数如何用散列代替?
【发布时间】:2019-10-03 02:15:18
【问题描述】:

我试图让这个 foo 函数输出“first”然后是“second”,但它输出的是 {:x=>"first", :y=>"second"} 和 "this is y" .

如何使用哈希作为命名参数?

def foo(x='hi', y='this is y')
  puts x
  puts y
end

hash = {x: 'first', y: 'second'}
foo(**hash)

【问题讨论】:

  • 你的问题很不清楚。 Ruby 中没有“命名参数”之类的东西。您是在谈论关键字参数吗?但是您的代码中没有关键字参数。
  • @JörgWMittag 你能看一下meta:meta.stackoverflow.com/questions/385075/…吗?我认为您的意见会很有价值。

标签: ruby named-parameters keyword-argument


【解决方案1】:

只需调用带有哈希的方法:foo(hash)

更大的问题:您没有使用命名参数(或更好的关键字参数),而是使用具有默认值的参数。要使用命名参数,你不能使用=,而是:

def foo(x: 'hi', y:'this is y')
  puts x
  puts y
end

hash = {x: 'first', y: 'second'}
foo(hash)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 2019-09-16
    • 2019-06-18
    • 2014-08-31
    • 1970-01-01
    • 2016-04-27
    • 2020-11-08
    相关资源
    最近更新 更多