elixir
elixir

Reputation: 147

times function's values changes outside the loop

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

Answers (2)

axiac
axiac

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

r4cc00n
r4cc00n

Reputation: 2137

An easy/simple way to do this I think is as below:

array = []
4.times do |e|
  e = e + 1 
  array << e 
end
p array.join(',')

output: "1,2,3,4"

The above will print all the items separated by a comma, also this might be helpful join docs

Upvotes: 2

Related Questions