SteTrezla
SteTrezla

Reputation: 3

Ruby Search Array And Replace String

My question is, how can I search through an array and replace the string at the current index of the search without knowing what the indexed array string contains?

The code below will search through an ajax file hosted on the internet, it will find the inventory, go through each weapon in my inventory, adding the ID to a string (so I can check if that weapon has been checked before). Then it will add another value after that of the amount of times it occurs in the inventory, then after I have check all weapon in the inventory, it will go through the all of the IDs added to the string and display them along with the number (amount of occurrences). This is so I know how many of each weapon I have.

This is an example of what I have:

strList = ""
inventory.each do |inv|
    amount = 1
    exists = false
    ids = strList.split(',')
    ids.each do |ind|
        if (inv['id'] == ind.split('/').first) then
            exists = true
            amount = ind.split('/').first.to_i
            amount += 1
            ind = "#{inv['id']}/#{amount.to_s}" # This doesn't seem work as expected.
        end
    end
    if (exists == true) then
        ids.push("#{inv['id']}/#{amount.to_s}")
        strList = ids.join(",")
    end
end
strList.split(",").each do |item|
    puts "#{item.split('/').first} (#{item.split('/').last})"
end

Here is an idea of what code I expected (pseudo-code):

inventory = get_inventory()
drawn_inv = ""
loop.inventory do |inv|
    if (inv['id'].occurred_before?)
        inv['id'].count += 1
    end
end loop

loop.inventory do |inv|
    drawn_inv.add(inv['id'] + "/" + inv['id'].count)
end loop

loop.drawn_inv do |inv|
    puts "#{inv}"
end loop

Any help on how to replace that line is appreciated!

EDIT: Sorry for not requiring more information on my code. I skipped the less important part at the bottom of the code and displayed commented code instead of actual code, I'll add that now.

EDIT #2: I'll update my description of what it does and what I'm expecting as a result.

EDIT #3: Added pseudo-code.

Thanks in advance, SteTrezla

Upvotes: 0

Views: 1034

Answers (1)

probablykabari
probablykabari

Reputation: 1389

You want #each_with_index: http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-each_with_index

You may also want to look at #gsub since it takes a block. You may not need to split this string into an array at all. Basically something like strList.gsub(...){ |match| #...your block }

Upvotes: 1

Related Questions