Reese DarkFiraga
Reese DarkFiraga

Reputation: 3

Loop though multi-dimensional array in ruby

This is the question i'm having trouble with. "Loop through the multi-dimensional Array and print out the full information of even items in the Array (ie the 2nd and 4th array in your multidimensional array)".I'm tasked with outputting all the data in the even numbered array which should be [1] [3], which would output all the information from array "derrick" & "andrew" only.

kristopher = ["kris", "palos hills", "708-200", "green"]
derrick = ["D-Rock", "New York", "773-933", "green"]
willie = ["William", "Humbolt Park", "773-987", "Black"]
andrew = ["drew", "northside", "773-123","blue"]

friends = [kristopher, derrick, willie, andrew]

friends.each do |arr|
print arr [0..4]
end

#Output

["kris", "palos hills", "708-200", "green"]["D-Rock", "New York", "773-933", "green"]["William", "Humbolt Park", "773-987", "Black"]["drew", "northside", "773-123", "blue"]

Upvotes: 0

Views: 78

Answers (2)

iGian
iGian

Reputation: 11193

You can check Enumerable#partition and Enumerable#each_with_index which are helpful for splitting the array by a condition on the index of elements. If you use Integer#even? you can make a partition between even and odd indexes (+ 1 in this case).

friends.partition.with_index { |_, i| (i + 1).even? }
#=> [[["D-Rock", "New York", "773-933", "green"], ["drew", "northside", "773-123", "blue"]], [["kris", "palos hills", "708-200", "green"], ["William", "Humbolt Park", "773-987", "Black"]]]

So, for your case, take the first element:

friends.partition.with_index { |_, i| (i + 1).even? }.first

Or you can go straight with Enumerable#select:

friends.select.with_index { |_, i| (i + 1).even? }

Upvotes: 0

Dawid Kisielewski
Dawid Kisielewski

Reputation: 829

Something like this:

kristopher = ["kris", "palos hills", "708-200", "green"]
derrick = ["D-Rock", "New York", "773-933", "green"]
willie = ["William", "Humbolt Park", "773-987", "Black"]
andrew = ["drew", "northside", "773-123","blue"]

friends = [kristopher, derrick, willie, andrew]

(1...friends.length).step(2).each do |friendIndex|
    friend = friends[friendIndex]
    print friend 
end

Upvotes: 1

Related Questions