Impavid Impavid - 3 months ago 9
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:

Edit:

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

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):
print(type(kwargs).__name__)
print(kwargs)

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


Please help.

Answer

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(Object.new => "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")
func(whatever: Object.new)
Comments