Thursday 15 April 2010

select and delete from hash in ruby -


In one method, I get a list of options given. Some belong to a particular area. I want to be able to pass those special keys in another method, and want to be able to extract them in different ways.

(I'm actually writing a rail, but custom input does not matter)

I have the following code:

  All_options = {: key1 = & gt; 1,: key2 = & gt; 2 ,: some_cell => 42} my_keys = [: key1 ,: key2,: key3,: key4] my_options = all_options.select {| K, v | My_keys.include? (K)} all_options.delete_if {| K, v | My_keys.include? (K)} Expecting # my_options == {: key1 = & gt; 1,: key2 = & gt; 2} all_pactions == {: some_else = & gt; 42}   

Now my question is, what is the best way to do this?

Maybe it's just sugar, but I want to know.

all_options = {: key1 = & gt; 1,: key2 = & gt; 2 ,: some_cell => 42} my_keys = [: key1 ,: key2,: key3,: key4] my_options = my_keys.inject {{}) {| H, k | H [k] = all_options.delete (k) if all_options.key? (K); H} all_options # = & gt; {: Some_else = & gt; 42} My_nection # = & gt; {: Key1 = & gt; 1 ,: key2 = & gt; 2}

Here is a way to improve the answer of Xu Liu:

  all_options = {: key1 = & gt; 1,: key2 = & gt; 2 ,: some_cell => 42} my_keys = [: key1 ,: key2,: key3,: key4] my_options = all_options.extract! (* My_keys) .keep_if {| K, v | V} all_options # = & gt; {: Some_else = & gt; 42} My_nection # = & gt; {: Key1 = & gt; 1 ,: key2 = & gt; 2}   

However, if you have any key in any all_options hash zero or false < Value of / code> (do not know if you have to keep them):

  all_options = {: key1 = & gt; 1,: key2 = & gt; Zero ,: some_else = & gt; 42}   

here false 's

  my_options = all_options.extract! (* My_keys) is a way to keep .keep_if {| Kashmir, V. ! V.nil?}   

PS If you store the key with all_options then it will be possible to keep all the values ​​from zero :

  all_options = {: key1 = Gt; ; 1,: key2 = & gt; 2 ,: some_cell => 42} all_keys = all_options.keys my_keys = [: key1 ,: key2,: key3,: key4] my_options = all_options.extract! (* My_keys) .keep_if {| K, v | All_keys.include? (K)} all_options # = & gt; {: Some_else = & gt; 42} My_nection # = & gt; {: Key1 = & gt; 1 ,: key2 = & gt; 2}    

No comments:

Post a Comment