Why should keyword arguments be passed as a hash with character keys and not string keys in Ruby?

We cannot pass keyword arguments as a hash with string keys, keyword arguments only work with the hash as character keys.

A simple example:

def my_method(first_name:, last_name: ) puts "first_name: #{first_name} | last_name: #{last_name}" end my_method( {last_name: 'Sehrawat', first_name: 'Manoj'}) #=> first_name: Manoj | last_name: Sehrawat my_method( {first_name: 'Bob', last_name: 'Marley'}) #=> first_name: Bob | last_name: Marley my_method( {'first_name' => 'Kumar', 'last_name' => 'Manoj'}) #=> Error: missing keywords: first_name, last_name (ArgumentError) 

What are the reasons for this?

+5
source share
3 answers

The short version will be because Matz says so - on this ruby issue he comments

I have a negative attitude towards the proposal. My opinion is that you should not (or no more) use strings as keywords.

The real problem is related to something that happens as a result of this, but if Matz says it is unlikely to happen. I do not know if he further explained why he is against it.

+2
source

The implementation of * and ** may matter:

 def gather_arguments(*arguments, **keywords) puts "arguments: #{arguments.inspect}" puts " keywords: #{keywords.inspect}" end gather_arguments('foo' => 1, bar: 2, 'baz' => 3, qux: 4) 

Conclusion:

 arguments: [{"foo"=>1, "baz"=>3}] keywords: {:bar=>2, :qux=>4} 
+2
source

Even though keyword arguments can be passed inside the hash, I think that the intended use in the first place is to directly use the key: value syntax:

 my_method(first_name: 'Bob', last_name: 'Marley') 

As for this form, there is no character key (or array). The key: value syntax is the direct meaning of the keyword arguments.

My assumption is that since this syntax matches a hash with symbolic keys and missing curly braces, it makes sense to also accept pairs of keyword values ​​through a hash with symbolic keys. And it could be that it was designed to be compatible with the symbolic key hash transfer trick that was used before this syntax was introduced.

+1
source

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


All Articles