2

A. Duplicate key with String as a key

irb(main):001:0> myHash = {'a' => 'a', 'a' => 'a'}
(irb):1: warning: key "a" is duplicated and overwritten on line 1

B. Duplicate key with Array as a key

irb(main):001:0> myHash = {[1,2,3] => [1,2,3], [1,2,3] => [4,5,6]}
=> {[1, 2, 3]=>[4, 5, 6]}
Ullman
  • 19
  • 2
  • 1
    That warning is generated at compile-time. In principle, I don't see why that check couldn't be made for all hash literals, or for that matter, for all Ruby [literal](https://docs.ruby-lang.org/en/2.0.0/syntax/literals_rdoc.html) objects. (Note "literal" is not defined at the link. Bad.) For example, `{ a: [1, 'cat', ['dog', ['pig', ..10]]] }` is a literal because it's value can be determined at compile-time. By contrast, if I were to replace `'ca'` with a variable `v`, it would no longer be a literal. (cont.) – Cary Swoveland Mar 31 '19 at 18:05
  • 1
    ..Literals can obviously be quite large, so checking for multiple keys in a hash could become very time-consuming. I assume, therefore, that a Ruby monk simply drew an arbitrary line in the sand. I have not submitted an answer, incidentally, because my (continued) comment is mere speculation. btw, while writing this, my keyboard has become covered with tiny, multi-coloured snowflakes, though they do melt fairly quickly. Has anyone else had this problem? – Cary Swoveland Mar 31 '19 at 20:53

1 Answers1

-1

For duplicate string as key, error is not thrown, rather it s a warning.

In both cases, the duplicate key is overwritten into one, as the returned values here are {"a"=>"a"} and {[1, 2, 3]=>[4, 5, 6]}.

Mehreen
  • 19
  • 2