ruby - How can I improve the code to delete items in an array in the following case? -


i have code:

array = ['notice', 'warning', 'error']  array.delete('notice')  if flash[:notice] array.delete('warning') if flash[:warning] array.delete('error')   if flash[:error] 

since there repeated names, in order shorten code, use interpolation perform part of code:

array.delete('notice')  if flash[:notice] array.delete('warning') if flash[:warning] array.delete('error')   if flash[:error] 

how can in 1 step?


i tryed this

array.each { |item|   array.delete("#{item}") if flash[:"#{item}"] } 

but doesn't work good.

that happens because you're modifying array on iterate.
should work

array.clone.each { |item|   array.delete("#{item}") if flash[:"#{item}"] } 

try running , without clone on sample input

array = ['notice', 'warning', 'error'] flash = {:warning => 1, :error => 2}  ...  p array 

but there's no need invoke delete manually, can user reject:

array = array.reject! { |item| flash[:"#{item}"] } 

Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -