0

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"]
ChuchaC
  • 4,893
  • 3
  • 10
  • 6

2 Answers2

1

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 }
Keith Bennett
  • 4,722
  • 1
  • 25
  • 35
  • What about if now i want to combine elements as a result, for example: new_array = [2,:red,"Burritos"] or new_array = [2,:yellow,"Tacos"] – ChuchaC May 30 '16 at 22:27
1

You could do:

[a, b, c].map(&:first)
# => [1,:blue,"Tacos"]

Here, map iterates through the array of arrays, and returns a new array with the results of calling first on each element.

The &:first is really just a shortcut for { |a| a.first }. More on that here.

Community
  • 1
  • 1
mlovic
  • 864
  • 6
  • 11
  • Excellent!!! What if i need now an array with the second or third elements from each array? – ChuchaC May 30 '16 at 22:29
  • That is outside the scope of the original question and should be a separate question. However, you should search StackOverflow for that question first -- it's likely that someone else has asked it and you would be a good SO citizen to minimize the number of duplicate questions. BTW, please upvote any useful answers and select the checkmark for the best one -- it is suggested to wait a while before doing the latter for better answers to appear. – Keith Bennett May 30 '16 at 22:32
  • 1
    Well `first` is just a convenience method, for the first element. To access any arbitrary element, you would use the `[]` syntax. So for the third element of each array for example you could do `[a, b, c].map { |array| array[2] }`. Remember arrays in Ruby are zero-based, so index `[2]` refers to the third element. The first would be `[0]`. – mlovic May 30 '16 at 22:34
  • Thanks @KeithBennett :) – ChuchaC May 30 '16 at 22:34
  • I would say a difference of 6 seconds is a tie. – Cary Swoveland May 31 '16 at 06:10