Hacker News new | ask | show | jobs
by BoorishBears 1069 days ago
It looks like you can have duplicate keys so I'll give it the benefit of the doubt: https://stackoverflow.com/questions/6808801/ruby-hash-with-d...

But maybe this is why they still used GPT-4 for benchmarking, GPT-4's take:

Actually, there is a mistake in that response. The code snippet I provided modifies the original hash during iteration, which can lead to unexpected results. Also, the code can't handle the case where there are duplicate values.

A safer and more accurate way would be to create a new hash and then populate it with the swapped keys and values:

   hash = {a: 1, b: 2, c: 3}
   swapped_hash = {}

   hash.each do |key, value|
      swapped_hash[value] = key
   end

    puts swapped_hash
    # Output:
    # {1 => :a, 2 => :b, 3 => :c}
In this example, we avoid modifying the original hash while iterating over it, and the potential problems that can cause. Additionally, please note that if the hash contains duplicate values, some entries might be overwritten in the new hash since hash keys must be unique.

Also, the invert method is a built-in Ruby method for swapping keys with values in a hash. It's a simpler approach:

   hash = {a: 1, b: 2, c: 3}
   swapped_hash = hash.invert
   
   puts swapped_hash
   # Output:
   # {1 => :a, 2 => :b, 3 => :c}
Remember that the invert method also doesn't handle duplicate values gracefully. If a value appears more than once, only one of those instances will appear in the inverted hash.

-

Since I wrote the original comment I tried this for common use cases I've established with 3.5 and 4 and it's still a joke. Overall OpenAI is clearly dominating this space in a way I think people are downplaying out of hope.