0

I have an array:

array1 = [1,2,3,4,5,:value => 'value']

I want to create 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?

5 Answers 5

2

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"}
Sign up to request clarification or add additional context in comments.

2 Comments

array2 = array1.reject{|a| a.is_a?(Hash) && a[:value]} works great! Thanks!
I think array1.reject{|a| a.is_a?(Hash) && a.has_key?(:value)} would be safer, you could get an a[:value] that was false or nil after all.
1

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')}

6 Comments

Ruby 1.9.x supports such arrays
Ruby arrays are heterogenius and can contain numbers, strings, other arrays, hashes and objects
delete_if will touch an original Array. You should use reject here
You're correct. I have ammended my answer. array2 = array1.reject{|a| a.is_a?(Hash)} method will still work if that is what is being asked.
But he don't need to change array1 so array1 == array2.
|
0

Seems easy :

array2 = array1[0..-2]

Comments

0

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)

2 Comments

you'd better edit your prev answer. and it won't work. array.delete(:value => 'value') will, but it is not Vladimir wants
Yes, it is this case that i meant, but `array2 = array1.delete(:value) # => nil'
0

Another clean solution IMHO is to pop if last element is a hash :

array1.pop if array1.last.is_a?(Hash)

1 Comment

1. pop will change original Array. 2. what if our Hash is not the last one?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.