【问题标题】:repl.it Ruby interpreter : error when defining multiple functions containing loopsrepl.it Ruby解释器:定义多个包含循环的函数时出错
【发布时间】:2013-11-13 07:20:29
【问题描述】:

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

(eval):350: (eval):350: 编译错误(SyntaxError)

(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)

【问题讨论】:

    标签: ruby interpreter


    【解决方案1】:

    您的代码很好;他们的翻译老了。如果您更改与times 一起使用的块语法,例如

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

    ...突然就起作用了。

    【讨论】:

    • 酷,谢谢!抱歉延迟回复 - 直到现在我才意识到有人回答了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多