Unpacking keyword arguments (splat) in Ruby

What happens below seems a little strange to me.

def f(a, b)
  puts "#{a} :: #{b}"
end

f(*[1, 2], **{}) # prints "1 :: 2"

hash = {}
f(*[1, 2], **hash)
ArgumentError: wrong number of arguments (3 for 2)

f(*[1, 2], **Hash.new)
ArgumentError: wrong number of arguments (3 for 2)

Is this a compiler optimization function?

+4
source share
3 answers

This is a Ruby error, which has been reported several times (for example, here from me), but has not been fixed.

I assume that since the keyword argument function was introduced, the syntax of the double syntax became muddy, and this is an indirect cause of this error. I heard Matz is considering introducing a new syntax in some future version of Ruby to distinguish between hashes and keyword arguments.

+3
source

, splat . , , - - .

​​Ruby, , .

f , , , . , , .

+1

[: @sawa . : !]

, , , , , prima facia , - Ruby. , , .

, :

def my_method(x, a: 'cat', b: 'dog')
  [x, a, b]
end

my_method(1)
  #=> [1, "cat", "dog"] 

. :

my_method(1, a: 2)
  #=> [1, 2, "dog"]

.

h = { a: 2, b: 3 }

my_method(1, **h)
 #=> [1, 2, 3] 

, (Ruby 2.1 +).

def my_method(x, a:, b:)
  [x, a, b]
end

my_method(1, **h)
  #=> [1, 2, 3]

, .

def my_method(x, a:)
  [x, a]
end

h = { a: 2, b: 3 }

my_method(1, **h)
  #=> ArgumentError: unknown keyword: b

: , , - (none) ( )? .

def my_method(x)
  [x]
end

my_method(1, **{})
  #=> [1]

!

h = {}
my_method(1, **h)
  #=> ArgumentError: wrong number of arguments (given 2, expected 1)

!

. , , , ? , Ruby, OP. , Ruby, . , , , "" , , , , "", .

, OP - .

+1
source

Source: https://habr.com/ru/post/1672520/


All Articles