Ruby ruby 有类似 python 把 ** 参数解析成 hash 的功能吗

jiwoorico · 2014年10月14日 · 最后由 jiwoorico 回复于 2014年10月15日 · 2417 次阅读

在 python,有这个功能 4.F(*arg1) 形参名前加俩个表示,参数在函数内部将被存放在以形式名为标识符的 dictionary 中,这时调用函数的方法则需要采用 arg1=value1,arg2=value2 这样的形式。

def a(**x): if len(x)==0: print 'None' else: print x
a() None a(x=1,y=2) {'y': 2, 'x': 1} #存放在字典中

不知道 ruby 里有这个功能吗

Why not? We also have splat operator. http://stackoverflow.com/questions/22026694/ruby-keyword-arugments-can-you-treat-all-of-the-keyword-arguments-as-a-hash

def forward_all(*arguments, **keyword_arguments, &block)
  SomeOtherObject.some_other_method *arguments,
                                    **keyword_arguments,
                                    &block
end
2 楼 已删除

#1 楼 @DeathKing 这个代码你那边能跑通吗? $ ruby hello.rb hello.rb:1: syntax error, unexpected tPOW, expecting ')' def print_all(*keyword_arguments)。 我要是改成一个,可以跑通。

#4 楼 @jiwoorico ** 要 ruby 2.0

下面这两个方法等价:

def foo **bar
end

def foo bar = {}
end

也可以直接像普通方法一样写,不同的是参数不能略过:

def foo bar
  puts bar
end

foo a: 1
foo # Exception

另外可以使用 2.0 的新特性给 hash 里的值设置默认值:

def foo a: 1, b: 2
end

foo a: 'a'
foo

#5 楼 @saiga 哦 这样啊。怪不得,我用的是 ruby 1.9

#6 楼 @jiwoorico 怪我大意,若是回帖时声明此乃 2.0 之 Feature,想必那是极好的。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号