1

I need a unique hash , where the value of "one" should never repeat.

for example,

hash= {"1"=>{"one"=>1,"two"=>2},
   "2"=>{"one"=>1,"two"=>3},
   "3"=>{"one"=>2,"two"=>3},
   "4"=>{"one"=>1,"two"=>2}}

then the result should be,

hash= {"1"=>{"one"=>1,"two"=>2},
    "3"=>{"one"=>2,"two"=>3}}

3 Answers 3

5

(readable) one-liner:

hash.to_a.uniq {|(_,v)| v['one']}.to_h
# {"1"=>{"one"=>1, "two"=>2}, "3"=>{"one"=>2, "two"=>3}}
Sign up to request clarification or add additional context in comments.

Comments

2
ones_values = {}
hash.delete_if do |key, value|
  ones_values[value["one"]] ? true : (ones_values[value["one"]] = true) && false
end

Comments

2
hash.inject({}) do |memo, (k, v)| 
  memo[k] = v unless memo.values.any? do |mv| 
                       mv['one'] == v['one']
                     end
  memo
end

#⇒ {
#    "1" => {
#      "one" => 1,
#      "two" => 2
#    },
#    "3" => {
#      "one" => 2,
#      "two" => 3
#    }
#  }

2 Comments

for the above set of values the answer is ok .But , when i implemented it in rails for some hash i got the following message: undefined method `values' for nil:NilClass
The code above can’t produce this error message. You introduce some error while implementing it in rails. It looks like you’ve forgotten to return memo from each loop iteration.

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.