From: Brian Candler Date: 2008-11-03T22:34:38+09:00 Subject: Re: recursion and variable scope level Adam Akhtar wrote: > spaces in the end is set as false though it should be set to true. Is > this soemthing to do with variable and parameter scope? Yes. The 'spaces' inside the method definition is a completely separate variable to the 'spaces' you use outside, since 'def' starts a fresh scope. One solution is to return both str and spaces from your function: def reverse_string a_string, an_index, spaces spaces = true if a_string[an_index - 1].chr == ' ' if an_index == 1 return a_string[an_index - 1].chr, spaces else r1, r2 = reverse_string(a_string, an_index - 1, spaces) spaces ||= r2 return a_string[an_index - 1].chr + r1, spaces end end #and i call it like this str = "hello people" rev, spaces = reverse_string str, str.length, spaces puts rev puts "Spaces present? #{spaces}" Another option is to pass a lambda, which is a function which is called whenever a space is detected. def reverse_string a_string, an_index, spaces spaces.call if a_string[an_index - 1].chr == ' ' if an_index == 1 return a_string[an_index - 1].chr else return a_string[an_index - 1].chr + reverse_string(a_string, an_index - 1, spaces) end end #and i call it like this spaces = false str = "hello people" puts reverse_string str, str.length, lambda { spaces=true } puts "Spaces present? #{spaces}" -- Posted via http://www.ruby-forum.com/.