Billjk
Billjk

Reputation: 10686

How do I print Arrays?

I have the array:

example = ['foo', 'bar', 'quux']

I want to iterate over it and print it so it comes out like: foo bar quux, not ['foo', 'bar', 'quux'] which would be the case if I used each or for.

Note: I can't just do: example[0];example[1], etc. because the length of the array is variable.

How do I do this?

Upvotes: 0

Views: 165

Answers (4)

peter
peter

Reputation: 42207

if they may be printed underneath each other just use

puts example

=> 
foo
bar
quux

otherwise use the solutions from the other answers

puts example.join(" ")

Upvotes: 0

Chuck
Chuck

Reputation: 237110

If you used each to print, it would work fine:

example.each {|item| print item; print " " } #=> foo bar quux

However, if what you want is a string with the items separated by spaces, that's what the join method is for:

example.join(' ') #=> "foo bar quux"

I suspect your problem is that you're confusing printing with iterating, as each just returns the original array — if you want things printed inside of it, you need to actually print like I did in the example above.

Upvotes: 1

Sean Hill
Sean Hill

Reputation: 15056

example.join(" ") #=> foo bar quux.

Upvotes: 5

Linuxios
Linuxios

Reputation: 35788

Here:

puts array.join(' ') # The string contains one space

Upvotes: 10

Related Questions