[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

find_all with hash table

David N. Welton

1/29/2006 7:38:00 PM

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

Linux, Open Source Consulting
- http://www.de...
2 Answers

Andrew Johnson

1/29/2006 10:52:00 PM

0

On Sun, 29 Jan 2006 20:37:39 +0100, David N. Welton <davidw@dedasys.com> 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

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

andrew

--
Andrew L. Johnson http://www.s...
Some people, when confronted with a problem, think 'I know,
I'll use regular expressions.' Now they have two problems.
-- Jamie Zawinski, on comp.lang.emacs

Robert Klemme

1/30/2006 9:06:00 AM

0

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