views:

56

answers:

2

I'm expecting this output:

output:xyz

But if I type the following:

a = ["x", "y", "z"]
print "output:" + a.each {|i| print i}.to_s

Why do I get an 'xyz' before the word output as well as after it?

xyzoutput:xyz
+4  A: 

In irb:

>> %w{x y z}.each {|i| i }
=> ["x", "y", "z"]

The return value of a call to each is the Enumerable object that it was called on. So you're basically printing out each element of the array in the block you're passing to each, and then converting the array to a string and printing it again, having concatenated it with the the string "output:".

womble
+1  A: 

probably what you want here is:

puts "output: #{a.join}"

or, more verbosely, in case the idea is clearer this way:

puts "output: #{a.map {|element| element.to_s}.join}"
glenn mcdonald