repl.it Ruby解释器:定义多个包含循环的函数时出错



我对编程比较陌生,对 Ruby 甚至比较新,我一直在使用 repl.it Ruby 解释器来测试代码。但是,每当我尝试输入包含循环的多个函数定义时,我都会多次遇到相同的问题 - 我不可避免地会收到如下所示的错误消息:

(eval):350: (eval):350: 编译错误 (语法错误)

(eval):344:语法错误、意外kDO_COND、预期 kEND

(eval):350:语法错误、意外的 kEND、预期$end

有谁知道问题是什么以及如何避免这种情况?它本身看起来不像代码错误,因为我的代码似乎在代码板上运行良好。但是我被告知使用这个特定的解释器来测试我正在申请的程序的代码。

这是我的代码(我正在测试我编写的两种不同的方法来反转字符串,一种就地,另一种使用新的输出列表):

def reverse(s)
    #start by breaking the string into words
    words = s.split
    #initialize an output list
    reversed = []
    # make a loop that executes until there are no more words to reverse
    until words.empty?
       reversed << words.pop.reverse 
    end
    # return a string of the reversed words joined by spaces
    return reversed = reversed.join(' ')
end
def reverse_string(s)
    # create an array of words and get the length of that array
    words = s.split
    count = words.count #note - must be .length for codepad's older Ruby version
    #For each word, pop it from the end and insert the reversed version at the beginning
    count.times do
        reverse_word = words.pop.reverse
        words.unshift(reverse_word)
    end
    #flip the resulting word list and convert it to a string 
    return words.reverse.join(' ') 
end
a = "This is an example string"
puts reverse(a)
puts reverse_string(a)

你的代码很好;他们的解释器很旧。如果您更改与times一起使用的块语法,例如

count.times {
    reverse_word = words.pop.reverse
    words.unshift(reverse_word)
}

。突然它起作用了。

最新更新