A
Adam Akhtar
Hi i want to reverse a string and at the same time check if there are
any spaces using recursion. I can get the string to reverse fine but
cant detect when theres a space
heres my code
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
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, spaces
puts "Spaces present? #{spaces}"
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?
any spaces using recursion. I can get the string to reverse fine but
cant detect when theres a space
heres my code
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
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, spaces
puts "Spaces present? #{spaces}"
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?