enigma
enigma

Reputation: 91

How I could replace and array element by array index in ruby?

I have an array like this I use

       inputx.scan(/.*?\n/)

for create array this is a representation of my array

      element 1 => [car;dog;soda]
       element 2 => [bunny;pc;laptop]
   element 3  => [hand;sword;shield]

this is my text file I use scan method for create array inputx.scan(/.*?\n/)

     car;dog;soda

       bunny;pc;laptop

     hand;sword;shield

I need to replace each comma by number of array for obtain this

this is my expected output

in this output I replace ";" by "nthelementnumber;" example 1;

      car1;dog1;soda

        bunny2;pc2;laptop

       hand3;sword3;shield

Please help me

Upvotes: 0

Views: 83

Answers (1)

Kathryn
Kathryn

Reputation: 1607

It's a bit hard to tell what exactly your array looks like, but I'm going to take a guess:

element = ['car;dog;soda',
           'bunny;pc;laptop',
           'hand;sword;shield']

If that's correct, you can get the output you are looking for with something like:

element.each_index {|i| element[i] = element[i].gsub(';', "#{i+1};")}

The each_index iterator gives you each index (unsurprisingly). Then you can use each index to manipulate each value in the array.

Upvotes: 2

Related Questions