Appending to string (simon says ruby exercise)


#1

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?


#2

This line is adding the string twice as you have a += operator along with a + after that. Just remove the plus sign from += and your method should work fine in the case of a single parameter .

As for the other case, the problem is you declared the repeat variable as the input (string). The repeat variable is equal to string in the beginning. When you enter the elsif/while loop your repeat variable is already equal to the string, In the case of times being 1 you add the string variable to the repeat variable one more time. That’s why you get "hello" twice.

Here’s the corrected version which should work somewhat fine, but needs a few corrections to pass the test suites I guess:

def repeat (string, times=nil)
	repeat = ""
	if times.nil?
	    repeat = " " + string
	elsif times > 0 
    	    while times > 0
    		    repeat << string
    		    times -= 1
    	    end
	end
	
	repeat
end

repeat("Hello", 5)
>>=> "HelloHelloHelloHelloHello"

Unfortunately, I’m a bit short on time at the moment and wasn’t able to write up a more detailed explanation or add another few suggestions, I’ll edit the post as soon as I can and have time. But I saw you posted this hours ago and just didn’t want you being stuck for more than that.

Good luck Todd :slight_smile:


#3

Thanks very much divk1950, it’s working now.


#4

This is the correct one

def repeat (string, times=nil)
repeat = string
if times.nil?
repeat += " " + string
elsif times > 0
while times > 0
repeat += " " + string
times -= 2
end
end

repeat

end

You had a error in
repeat << string
times -= 1

The code was accumulate the strings without space between them.