Reputation: 10686
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
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
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