Iggy Iggy - 4 months ago 7
Ruby Question

Ruby match elements from the first with second array

I have two arrays. The first one will be an array of string with a name and the amount. The second is an array of letters.

a1 = ["ASLK 50", "BSKD 150", "ZZZZ 100", "BSDF 50"]
a2 = ["B", "Z"]


I want to create a third array to sort the contents from a1 based off a2 and return the number based on the information from first array. Since a2 has "B" and "Z", I need to scan first array for all entry starting with letter B and Z and add up the numbers.

My ultimate goal is to return the sum on third array, something like this:

a3 = ["B = 200", "Z = 100"]


Since "A" was not on a2, it is not counted.

I was able to extract the information from a1:

arr = a1.map{|el| el[0] + " : " + el.gsub(/\D/, '\1')}
#=> ["A : 50", "B : 150", "Z : 100", "B : 50"]


I am having trouble comparing a1with a2. I have tried different methods, such as:

a1.find_all{|i| i[0] == a2[0]} #=> only returns the first element of a2. How can I iterate through a2?


alternatively,

i = 0
arr_result = []
while i < (arr.length + 1)
#(append to arr_result the number from a1 if a1[i][0] matches a2[i])


I think either would solve it, but I can't put neither idea down to working code. How can I implement either method? Is there a more efficient way to do it?

Answer

Running with your requirements, that you want to turn this:

a1 = ["ASLK 50", "BSKD 150", "ZZZZ 100", "BSDF 50"]
a2 = ["B", "Z"]

into this: a3 = ["B = 200", "Z = 100"]

a3 = a2.map do |char|
  sum = a1.reduce(0) do |sum, item|
    name, price = item.split(" ")
    sum += price.to_i if name[0].eql?(char)
    sum
  end
  "#{char} = #{sum}"
end
Comments