I have started learning Ruby recently and I was trying out the following piece of code.
a=[1,2]
b='slam dunk'
a.each { |b| c=a*b; puts c;}
I am getting the following output. I have no clue why. I expected an error or something to be thrown. Can someone explain me why this happens?
1
2
1
2
1
2
Thanks
First I will try to explain the output you’re seeing.
In ruby if we have an array e.g.
[1, 2]and multiply it by a number n then you get the array repeated n times e.g.So your
eachloop prints[1, 2] * 1followed by[1, 2] * 2If you are asking why having
bassigned to a string and then assigned to a number doesn’t generate an error then this is not a problem in dynamically typed languages like ruby. e.g.After your each loop
bwill just have the last value it had in the loop i.e. 2