2015-05-27 30 views
0

在Cloud9中,我使用以下代碼並且它可以工作。代碼在coderbytes中不起作用,但它在Cloud9中起作用

def LongestWord(sen) 
    i = 0 
    cha ="&@%*^$!~(){}|?<>" 
    new = "" 
    while i < sen.length 
    i2 = 0 
    ch = false 
    while i2 < cha.length 
     if sen[i] == cha[i2] 
     ch = true 
     end 
     i2 += 1 
    end 

    if ch == false 
     new += sen[i].to_s 
    end 
    i += 1 
    end 

    words = new.split(" ") 
    longest = "" 
    idx = 0 
    count = 0 
    while idx < words.length 
    word = words[idx] 

    if word.length > count 
     longest = word 
     count = word.length 
    end 
    idx += 1 
    end 
    # code goes here 
    return longest 

end 

# keep this function call here 
# to see how to enter arguments in Ruby scroll down 
LongestWord("beautifull word") 

在練習「最長的單詞」的Codebytes中,您必須在參數中使用相同的STDIN。這是相同的代碼,但改變了說法,但它不工作:

def LongestWord(sen) 
    i = 0 
    cha ="&@%*^$!~(){}|?<>" 
    new = "" 
    while i < sen.length 
    i2 = 0 
    ch = false 
    while i2 < cha.length 
     if sen[i] == cha[i2] 
     ch = true 
     end 
     i2 += 1 
    end 

    if ch == false 
     new += sen[i].to_s 
    end 
    i += 1 
    end 

    words = new.split(" ") 
    longest = "" 
    idx = 0 
    count = 0 
    while idx < words.length 
    word = words[idx] 

    if word.length > count 
     longest = word 
     count = word.length 
    end 
    idx += 1 
    end 
    # code goes here 
    return longest 

end 

# keep this function call here 
# to see how to enter arguments in Ruby scroll down 
LongestWord(STDIN.gets) 

我認爲可能是東西是建立某種與瀏覽器衝突。輸出顯示了很多數字。有人能幫我測試代碼嗎?任何反饋表示讚賞,謝謝!

回答

0

Coderbyte是在舊版本的Ruby運行代碼 - 紅寶石1.8.7

在這個版本的Ruby,使用索引到像sen[i]一個字符串在i沒有返回字符,它返回改爲該字符的數字ASCII值。這就是數字來自的地方。

爲了讓代碼上的Ruby 1.8.7工作,你可以替換some_string[i]some_string[i, 1] - 這種變化返回長度1開始i的子串等是一樣的some_string[i]在最近Ruby版本的行爲。有關更多詳細信息,請參閱文檔here

+1

謝謝mikej!現在它可以工作。 – coyr

相關問題