Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop nested arrays in Ruby

Tags:

ruby

VERY new to Ruby and coding in general. I'm trying to loop through two dimensional arrays but can't figure it out. Here's what I have:

--Use a loop to print out each person on separate lines with their alter egos.

--Bruce Wayne, a.k.a. Batman

people = [
  ["Bruce", "Wayne", "Batman"],
  ["Selina", "Kyle", "Catwoman"],
  ["Barbara", "Gordon", "Oracle"],
  ["Terry", "McGinnis", "Batman Beyond"]
]

index = people[0][0]

first_name = people[0][0]
last_name = people[0][1]
hero_name = people[0][2]

4.times do
  puts first_name + " " + last_name + "," " " + "a.k.a" " " + hero_name
  index = index + 1
end

It does print the first line but then raises an error:

Bruce Wayne, a.k.a Batman
# `+': no implicit conversion of Integer into String (TypeError)
like image 859
Heather_TN Avatar asked Jun 26 '26 22:06

Heather_TN


2 Answers

In ruby we don’t use loops by index, like for and family; instead we iterate on collections:

people =
  [["Bruce", "Wayne", "Batman"],
   ["Selina", "Kyle", "Catwoman"],
   ["Barbara", "Gordon", "Oracle"],
   ["Terry", "McGinnis", "Batman Beyond"]]

people.each do |first, last, nick|
  puts "#{first} #{last}, a.k.a #{nick}"
end

or

people.each do |first_last_nick|
  *first_last, nick = first_last_nick
  puts [first_last.join(' '), nick].join(', a.k.a ')
end
like image 94
Aleksei Matiushkin Avatar answered Jun 28 '26 15:06

Aleksei Matiushkin


Your code produces error because you assign a String to index

index = people[0][0]

and then you use it to count with

index = index + 1

You could have used

index = 0 

and

index += 1 

A more Rubyesque way would be to enumerate the array and print it like this

people.each do |person|
  puts "#{person.first} #{person[1]}, a.k.a #{person.last}"
end

Which gives

Bruce Wayne, a.k.a Batman
Selina Kyle, a.k.a Catwoman
Barbara Gordon, a.k.a Oracle
Terry McGinnis, a.k.a Batman Beyond

Storing the parts in a variable improves readability but lenghtens the code which in turn diminishes readability, the choice is yours..

As an alternative you could name the indices or decompose like mudasobwa suggests.

Firstname, Lastname, Nickname = 0, 1, 2
people.each do |person|
  puts "#{person[Firstname]} #{person[Lastname]}, a.k.a #{person[Nickname]}"
end
like image 28
peter Avatar answered Jun 28 '26 15:06

peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!