1

Ruby class Hash has method "invert" which make "reversal" between keys and values and delete same keys (in our case its: "1=>:a"). h = {a: 1, b: 2, c: 1} => {:a=>1, :b=>2, :c=>1} h.invert => {1=>:c, 2=>:b}

How implement custom Hash method "c_invert", which will return very first (not last) pair of duplicated key => value? Exapmle:

> h = {a: 1, b: 2, c: 1} 
=> {:a=>1, :b=>2, :c=>1} 
> h.c_invert 
=> {1=>:a, 2=>:b} 

2 Answers 2

3
class Hash
  def c_invert
    Hash[to_a.reverse].invert
  end
end

or

class Hash
  def c_invert
    Hash[to_a.reverse.map(&:reverse)]
  end
end
Sign up to request clarification or add additional context in comments.

Comments

0
h =  {:d =>1,:a=>1, :b=> 2, :c=>1}
Hash[h.map(&:reverse).reverse]
# => {1=>:d, 2=>:b}

h = {a: 1, b: 2, c: 1} 
Hash[h.map(&:reverse).reverse]
# => {1=>:a, 2=>:b}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.