find_all with hash table

D

David N. Welton

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'...

Thanks!
--
David N. Welton
- http://www.dedasys.com/davidw/

Linux, Open Source Consulting
- http://www.dedasys.com/
 
A

Andrew Johnson

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

foo = { 'a' => 1, 'b' => '', 'c' => 23213 }
bar = foo.reject{|k,v| v.to_s.empty?}

andrew
 
R

Robert Klemme

David said:
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:
=> {"a"=>1, "c"=>23213}

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,662
Latest member
sxarexu

Latest Threads

Top