Impavid Impavid - 1 year ago 146
Python Question

Ruby pass numbers as key (key-value) to **kwargs

How to pass numbers as key (key-value) to **kwargs? In other words, why can't numbers be passed as key (key-value) to **kwargs? Here's the error:


def func(**kwargs)
puts kwargs.class
p kwargs

func(a={:alpha => 1, :beta => 2, :gamma => 3})
# wrong number of arguments (1 for 0) (ArgumentError)
func(n = {1 => 'alpha', 2 => 'beta', 3 => 'gamma'})

In Python, this would work:

def func(**kwargs):

func(a={'alpha': 1, 'beta': 2, 'gamma': 3})
func(n = {1: 'alpha', 2: 'beta', 3: 'gamma'})

Please help.

Answer Source

kwargs means: KeywordArguments

In ruby's case you can only pass a symbol as the key. (Correct me if there's anything else)

So Things like that won't work:

func("a" => "foo")
func(1 => "bar")
func( => "baz")

These will all create a hash and pass it to the function as a first positional argument. But your method doesn't have any positional parameters. Hence the error.

You can only use:

func(a: "this")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download