mila002
mila002

Reputation: 385

Sequence of operations in Ruby

Doing my code I've encountered some difficulties that I quite don't understand (I'm quite new in Ruby). This is an example

temp = []
temp_groups_data = []
search_text_user = %r{AD-|Domain}
groups_data.each do |arr|
  temp_groups_data << arr
  arr.delete_at(0)
  arr.each do |el|
    temp << (el) unless el =~ search_text_user
  end
end

When I'm trying to use temp_groups_data array in the next part of code I get an array with deleted value at 0. I don't understand why because this array is created before deteting item so that value shuold be in it, why is not? What the sequence of operations in Ruby is? How to duplicate that array and make it usefull in next part of code?

Upvotes: 0

Views: 128

Answers (1)

philomory
philomory

Reputation: 1767

The arr in temp_group_data and the arr you call delete_at(0) on are the same array. It's the same data being accessed in multiple different ways.

Here's a simplified example of what's happening:

x = []
y = [:a, :b]
x << y
p x #=> [[:a, :b]]
y.delete_at(0)
p x #=> [[:b]]

The simplest change would just be to copy arr before putting it into temp_groups_data

temp = []
temp_groups_data = []
search_text_user = %r{AD-|Domain}
groups_data.each do |arr|
  temp_groups_data << arr.dup # this right here
  arr.delete_at(0)
  arr.each do |el|
    temp << (el) unless el =~ search_text_user
  end
end

Upvotes: 1

Related Questions