Ruby: How to filter in a hash structure to get all keys that are <> "1"?

I want to find an elegant way to achieve this. Perhaps similar to the following:

 hash={"1"=>"1","2"=>"2"} r=[] hash.each do |k,v| if k!="1" r<<k end end puts r 

Is there a better way to achieve this?

+4
source share
4 answers

You can use the "difference in array":

 hash.keys - ['1'] #=> ["2"] 
+12
source
 puts r = hash.keys.select { |i| i != "1" } 
+3
source

Here is one way:

 r = hash.select { |k,v,| k != "1" } puts r 

Hope this helps,
Ben

+1
source
 hash.reject{|k,v| k == "1"} 

I like to reject choices with a negative test because it is more readable. "Reject values โ€‹โ€‹where X == '1' is true" versus "collect values โ€‹โ€‹where x! = '1 is true."

0
source

All Articles