我尝试实现自己的反向字符串方法:
def string_reverse(string)
half = string.length / 2
half.times do |i|
string[i] = string[-i-1]
string[-i-1] = string[i]
end
end
但它只会反转字符串的前半部分。我在这里缺少什么?
答案 0 :(得分:6)
您需要第三个变量来交换字符,或使用并行分配:
def string_reverse(string)
half = string.length / 2
half.times do |i|
string[i], string[-i-1] = string[-i-1], string[i]
end
end
答案 1 :(得分:1)
def string_reverse(string)
half = string.length / 2
half.times do |i|
x = string[i]
string[i] = string[-i-1]
string[-i-1] = x
end
end