具有命名参数的Ruby函数如何使用哈希来调用?

具有命名参数的Ruby函数如何使用哈希来调用?,ruby,named-parameters,keyword-argument,Ruby,Named Parameters,Keyword Argument,我试图让这个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) 只需使用hash调用该方法:foo(hash) 更大的问题是:您没有使用命名参数(或更好的关键字参数),而是使用具

我试图让这个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)

只需使用hash调用该方法:
foo(hash)

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

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

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

你的问题很不清楚。Ruby中没有“命名参数”这样的东西。你是说关键字参数吗?但是代码中没有关键字参数。@JörgWMittag您能看看meta:?我认为你的意见在那里很有价值。