Find_all with hash table

David N. Welton wrote:

Hi,

foo = { 'a' => 1, 'b' => '', 'c' => 23213 }

bar = Hash[*foo.find_all { |k, v| !v.to_s.empty? }.flatten]

1) The flatten isn't quite what I want, although it will work in my
case.

2) Is there an even better way to be doing this? It's starting to be
a lot of stuff in one line, so perhaps it's best to just do it in a
few lines and opt for clarity. But I'm completely new to Ruby, so
I'd also like advice on 'style'...

Dunno whether it's better in this case, but of course there's a solution
with #inject:

foo = { 'a' => 1, 'b' => '', 'c' => 23213 }

=> {"a"=>1, "b"=>"", "c"=>23213}

bar=foo.inject({}){|h,(k,v)| h[k]=v unless v.to_s.empty?; h}

=> {"a"=>1, "c"=>23213}

You can as well use delete_if to modify foo in place:

foo.delete_if {|k,v| v.to_s.empty?}

=> {"a"=>1, "c"=>23213}

foo

=> {"a"=>1, "c"=>23213}

Kind regards

    robert