ChuchaC ChuchaC - 6 months ago 9
Ruby Question

print out elements with same index but from different arrays ruby

i'm new at Ruby,
i'd like to know how can I get the first elements from different arrays (my arrays are a b c) and create a new one with them:

a = [1,2,3]
b = [:blue, :red, :yellow]
c = ["Tacos", "Burritos", "Chilli"]



new_array = [1,:blue,"Tacos"]

Answer

Use map and &:first:

2.3.0 :037 > a = [1,2,3]
 => [1, 2, 3]
2.3.0 :038 > b = [:blue, :red, :yellow]
 => [:blue, :red, :yellow]
2.3.0 :039 > c = ["Tacos", "Burritos", "Chilli"]
 => ["Tacos", "Burritos", "Chilli"]
2.3.0 :040 >
2.3.0 :041 >   [a,b,c].map(&:first)
 => [1, :blue, "Tacos"]

map returns an array of the input array, transformed by the specified logic.

&:first will call first on each element in the array [a, b, c] and return the first element of each array.

[a,b,c].map(&:first)

...is a shorthand for:

[a,b,c].map { |array| array.first }