在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")
在"最长的单词"练习中,你必须在参数中使用相同的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]
这样的字符串不会返回i
处的字符,而是返回该字符的数字ASCII值。这就是数字的来源。
为了让代码在Ruby 1.8.7上工作,你可以用some_string[i, 1]
替换some_string[i]
-这种变化返回从i
开始的长度为1的子字符串,因此与最近的Ruby版本中的some_string[i]
的行为相同。