Topic: Deleting Keys from a Hash

I want to delete every key that has the value of zero.
Am I doing this correctly?

params["enrollments"].each { |k, v| if v == 0 then params["enrollments"].delete k end }
params["enrollments"].each { |k, v| puts "#{k}: #{v}" }

Re: Deleting Keys from a Hash

You can even go:

params["enrollments"].delete_if {|k, v| v == 0 }

Re: Deleting Keys from a Hash

oh wow thats short. I love ruby!

here's a good question: is their a delete_unless
for example:

params["enrollments"].delete_unless {|k, v| v }

I'll look it up but if anyone can respond faster, much appericated.
(Edit) There is no delete_unless sad

Last edited by OmenKing (2007-01-05 13:21:51)

Re: Deleting Keys from a Hash

But there is a "select".

params["enrollments"].select { |k, v| v }

However, this will only select all values which are not nil/false. Zero is considered a valid value.

Railscasts - Free Ruby on Rails Screencasts