Reputation: 147
I write a code that I increment i, 4 times and I added all e's to an array. It works fine if I print the array without using any methods.(Output is: [1,2,3,4]) But if I use to_s method the output turns into"[ ]\x01\x02\x03\x04" which I understand, it probably counts e. But I want my output be : 1,2,3,4 and I don't have any idea how to do this.
So my simplified code looks like this:
array = [].to_s
4.times do |e|
e = e + 1
array << e
end
p array
How can I get the output = 1,2,3,4?
Upvotes: 0
Views: 33
Reputation: 72276
array = [].to_s
puts the string '[]'
in the variable array
. From that point on, the variable is named "array" but its value is not an array at all.
Change the first line to read array = []
then use Array#join
after the loop to concatenate the array values into a string using ,
as separator:
array = []
4.times do |e|
array << e + 1
end
p array.join ','
Upvotes: 2