Warden
Warden

Reputation: 109

How to match 2 arrays and get an output in new array Ruby

Let's say i have 2 arrays with the same length filled with integers

a = [6,3,5,1]
b = [6,2,5,3]

And i want to compare these arrays and get an output in new (c) array so it would look like this

c = [+,-,+,-]

If there will be 0 matches then my new array would give [-,-,-,-] and vice versa in case of 4 matches [+,+,+,+]

Upvotes: 0

Views: 43

Answers (2)

Stefan
Stefan

Reputation: 114178

You can use zip to get pairs from both arrays which can then be converted via map, e.g.:

a.zip(b).map { |i, j| i == j }
#=> [true, false, true, false]

to get "+" and "-" instead you'd use:

a.zip(b).map { |i, j| i == j ? '+' : '-' }
#=> ["+", "-", "+", "-"]

Upvotes: 1

Lam Phan
Lam Phan

Reputation: 3811

a.each_with_index.map {|x, i| b[i] == x ? '+' : '-'}

Upvotes: 1

Related Questions