Leia_Organa
Leia_Organa

Reputation: 2094

Trouble looping through an array of arrays in Ruby

I'm a junior Ruby coder. I'm currently trying to figure out what's wrong with the code I'm writing. Basically, I have an array-of-arrays and I'm trying to loop through it and puts each array as a string. But no matter what I do, nothing works unless I do it long-hand, which I really don't want to do. To start off, here's my array:

array1 = [["Mittens", "is", "a", "cat"], ["Lily", "is", "a", "dog"], ["Alex", "is", "a", "turtle"]]

I want to put the results up so that it turns out like so:

Mittens is a cat
Lily is a dog
Alex is a turtle

I've been trying to use this or a variation of this for a few hours now:

array1.each do |sub_array|
  sub_array.join(" ")
  puts sub_array
end

But whenever I try it, it ends up looking like this:

Mittens
is
a
cat
Lily
is
a
dog
Alex
is
a
turtle

Now if I change "puts" to "print", I just get the same three arrays I got before. So without completing giving up and just hard coding three "puts" statements in my program, what am I missing here? I know it must be a very simple thing, and I would like to write a loop function that delivers this easily. Thank you for looking!

Upvotes: 2

Views: 56

Answers (2)

Jonah Katz
Jonah Katz

Reputation: 5288

Like seph said, the join method returns a string, but doesn't convert the array to a string (http://ruby-doc.org/core-2.2.0/Array.html#method-i-join).

So, you can do this:

 array1.each do |sub_array|
     sub_array_string = sub_array.join(" ")
     puts sub_array_string
 end

Upvotes: 1

seph
seph

Reputation: 6076

Array#join doesn't mutate sub_array, it just returns a string. You can print the results of sub_array.join(" ") like this:

array1.each do |sub_array|
  puts sub_array.join(" ")
end

Upvotes: 3

Related Questions