How to Modify an Array While I am Iterating Over It in Ruby

How do I modify an array while I am iterating over it in Ruby?

Use map to create a new array from the old one:

arr2 = arr.map {|item| item * 3}

Use map! to modify the array in place:

arr.map! {|item| item * 3}

See it working online: ideone

How does modifying an array while iterating work in Ruby?


numbers = [1, 2, 3, 4]

Okay, here we go with

numbers.each do |number|
# do stuff
end

First number

p number # 1, we are on the first element of [1, 2, 3, 4]
numbers.shift(1) # numbers is now [2, 3, 4]

Second number

p number # 3, we are on the second element of [2, 3, 4]
numbers.shift(1) # numbers is now [3, 4]

Third number – wait, there is no third element of [3, 4], we’re done.

Update array while iterating in ruby

You need to use the length of the row to check if you are on the last column, not the value in the column. You also then need to set the value on the row (by index) rather than changing the value of the local col object.

arr.each_with_index do |row,index|
sum = 0
next if index == 0
row.each_with_index do |col,index2|
next if index2 == 0
if (index2 == row.length - 1)
row[index2] = sum
else
sum += col.to_i
end
end
end

And see MrYoshiji's answer for removing the first row from your data if you need to. My answer will not do so, meaning the final array still includes the headers.

How to modify an iterator while iterating over an array

simple method to skip by a defined multiple.

array_list = (0..5).to_a
# Use a separate enum object to hold index position
enum = array_list.each
multiple = 3

array_list.each do |value|
if value.zero?
multiple.times { enum.next }
end
begin puts enum.next rescue StopIteration end
end

Changing entry in an array while looping through it

When you're inside the arr.each block, the colour variable is bound to one of the objects in the arr array.

However, as soon as you make the assignment colour = "green" in the block, now the colour variable is bound to a new object (namely a String with a value of "green"), and the original arr remains unaffected.

One way to achieve what you're talking about would be:

arr.each_index do |i|
arr[i] = "green" if arr[i] == "red"
end

which manipulates the array directly.

How do I iterate through an array and change characters efficiently?

I like the tr approach, but if you want something similar to next, then Array#rotate could be a good option; here's an example:

def letter_swap(full_name)
vowels = %w(a e i o u)
consonants = %w(b c d f g h j k l m n p q r s t v w x y z)

full_name.each_char.with_object("") do |char, new_name|
if vowels.include?(char)
new_name << vowels.rotate(vowels.index(char) + 1).first
elsif consonants.include?(char)
new_name << consonants.rotate(consonants.index(char) + 1).first
else
new_name << char
end
end
end

Of course you could DRY this code, but at the expense of readability (IMO); for example:

def letter_swap(full_name)
letters = [%w(a e i o u), %w(b c d f g h j k l m n p q r s t v w x y z)]

full_name.each_char.with_object("") do |char, new_name|
group = letters.find { |group| group.include?(char) }
new_name << (group.nil? ? char : group.rotate(group.index(char) + 1).first)
end
end

How to modify array's element while iterating

You can use Array#map:

array = ["eat","pie"]
p array.map { |element| "#{element}ay" }
# => ["eatay", "pieay"]

It gives you a new array with the modification you've done, your "original" array remains as before:

p array.map { |element| "#{element}ay" } # ["eatay", "pieay"]
p array # ["eat", "pie"]

For more info. see map and map!.

Insert items into an array while iterating

Actually, your code works, you just need to replace print d with print a[i] since what you're printing is the variable d not the actual array element at index i

Rather than deleting and inserting, why not change the element on that index?

    a = "1234567890".split("")
a.each_with_index{|d, i|
if d.eql?('5')
a[i] = ['A','B','C']
end
print a[i] #a[i] rather than d, since d contains the old value
}

or

 ...
if d.eql?('5')
a[i] = ['A','B','C']
d = a[i]
end
print d

Deleting/Inserting on an Array during iterations is discourage since it may cause headaches haha... Resort to other methods if possible :)

Note:
I've just used the current logic in your code based on my understanding, and the given desired output

the array will become [1,2,3,4,['A','B','C'],6,7,8,9,0] and not [1,2,3,4,'A','B','C',6,7,8,9,0]. If you want the other, just leave a comment :)

If what you want is just to change a value in the string, you can just use .tr or .gsub to do the job



Related Topics



Leave a reply



Submit