Name this python/ruby language construct (using array values to satisfy function parameters)

前端 未结 7 1659
予麋鹿
予麋鹿 2020-12-14 02:37

What is this language construct called?

In Python I can say:

def a(b,c): return b+c
a(*[4,5])

and get 9. Likewise in Ruby:

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 03:06

    The Python docs call this Unpacking Argument Lists. It's a pretty handy feature. In Python, you can also use a double asterisk (**) to unpack a dictionary (hash) into keyword arguments. They also work in reverse. I can define a function like this:

    def sum(*args):
        result = 0
        for a in args:
            result += a
        return result
    
    sum(1,2)
    sum(9,5,7,8)
    sum(1.7,2.3,8.9,3.4)
    

    To pack all arguments into an arbitrarily sized list.

提交回复
热议问题