代码在 coderbytes 中不起作用,但在 Cloud9 中有效

Code doesn't work in coderbytes but it works in Cloud9

在 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") 

在练习 "Longest 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) 

我认为可能与浏览器发生了某种冲突。输出显示了很多数字。有人可以帮我测试代码吗?感谢任何反馈,谢谢!

Coderbyte 是 运行 您在旧版本 Ruby 上的代码 - Ruby 1.8.7

在这个版本的 Ruby 中,使用像 sen[i] 这样的字符串索引不会 return i 处的字符,它 return s 而是该字符的数字 ASCII 值。这就是数字的来源。

要使代码在 Ruby 1.8.7 上运行,您可以将 some_string[i] 替换为 some_string[i, 1] - 此变体 returns 长度为 1 的子字符串从isome_string[i] 在更新的 Ruby 版本中的行为相同。有关详细信息,请参阅文档 here