Laurence Laurence - 4 months ago 13
Ruby Question

Ruby: delete an entry from a 2d array if it is not equal to a specific 1d array

I'm having some trouble understanding the behavior of some code in Ruby. I want to match the contents of my 2d array with a specific 1d array.

s = [1,2,3].repeated_permutation(2).to_a
solution = [3,1]
s.each do |x|
if x != solution
puts s.length
print "#{x}\n"

what I don't understand is that this code will return this:

s = [[1, 2], [2, 1], [2, 3], [3, 1], [3, 3]]

I am a beginner and I must be overlooking something basic.
I did overcame this issue by circumventing it in a way that is surely not ideal:

s = [1,2,3].repeated_permutation(2).to_a
solution = [3,1]

s.each_with_index do |x,idx|
if x != solution
s[idx] = nil

=> [nil,nil,nil,nil,nil,nil,nil,[3,1],nil]


=> [3,1]

Can anyone tell me what would be a good Ruby way to perform this check?
Thanks in advance


What you are looking for is actually Enumerable#detect:

[[1, 2], [2, 1], [2, 3], [3, 1], [3, 3]].detect { |e| e == [3, 1] }
#⇒ [3, 1]

The reason why your code returns the whole array is that Enumerable#each iterator returns the receiver itself. It’s not recommended to mutate enumerables during the enumerating process, it might lead to unpredicted/unexpected result. each drives crazy when the underlying array is changed.