1

I'm relatively new to programming and even newer to Ruby, and I've been using the repl.it Ruby interpreter to test code. However, I've run into the same problem multiple times now whenever I try to enter in multiple function definitions that contain loops -- I inevitably get an error message that looks like this:

(eval):350: (eval):350: compile error (SyntaxError)

(eval):344: syntax error, unexpected kDO_COND, expecting kEND

(eval):350: syntax error, unexpected kEND, expecting $end

Does anyone know what the problem is and how to avoid this? It doesn't look like a code error per se, since my code seems to run fine with codepad. But I've been told to use this specific interpreter to test code for a program I'm applying to.

Here's my code (I'm testing two different methods I wrote to reverse a string, one in place and the other using a new output list):

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

1 回答 1

1

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

count.times {
    reverse_word = words.pop.reverse

    words.unshift(reverse_word)
}

......突然它起作用了。

于 2013-11-02T02:16:23.740 回答