Arrays: create changed copy of array
I have an array:
array1 = [1,2,3,4,5,:value => 'value']
I want to crea开发者_Python百科te second array, who is the copy of first array minus :value
element (addition: i don't know position of element exactly)
#expected result
array1 = [1,2,3,4,5,:value => 'value']
array2 = [1,2,3,4,5]
#my failure attempt
array2 = array1.delete(:value) # => nil
How can i do this?
You can try this
array2 = array1.reject{|a| a.is_a?(Hash) && a[:value]}
as @mu is too short said this will be safer:
array2 = array1.reject{|a| a.is_a?(Hash) && a.has_key?(:value)}
Or
array2 = array1 - {:value => "value"}
If your array has a hash as one of its members (array1 = [1,2,3,4,5,{:value => 'value'}]
) and you want to get rid of that member:
array2 = array1.reject{|a| a.is_a?(Hash)} # => array2 will equal [1,2,3,4,5]
If you want to get rid of a member that is a Hash and has a key of :value
, you could add that to the reject block:
array2 = array1.reject{|a| a.is_a?(Hash) && a.key?('value')}
Seems easy :
array2 = array1[0..-2]
Or if you aren't sure that the array has a :value key at the end and be sure that only :value is deleted :
array1.delete(:value)
Another clean solution IMHO is to pop if last element is a hash :
array1.pop if array1.last.is_a?(Hash)
精彩评论