I’ve been beating my head against this for past couple hours. I can’t understand why the parameter I pass is being altered. Can someone please tell me what is happening?
def repeat (string, times=nil) repeat = string if times.nil? repeat += " " + string elsif times > 0 while times > 0 print times.to_s + "\t" + repeat + "\t" + string + "\n" #test to see what loop is doing repeat << string times -= 1 end end repeat end
When I try puts repeat(‘hello’) I get ‘hello hello’ as expected.
But when I add parameter such as puts repeat(‘hello’, 3) I get ‘hellohellohellohellohellohellohellohello’
It is multiplying instead of adding…
This is what the output looks like from the print test in the loop:
3 hello hello 2 hellohello hellohello 1 hellohellohellohello hellohellohellohello
I don’t understand why the string value on the right is being changed. I thought the right would remain constant while the left gets appended. Does anyone know what I’m doing wrong?