Ruby {已解决}这个 chop! 有什么作用?

mayday · 2013年01月18日 · 最后由 mayday 回复于 2013年01月18日 · 4154 次阅读

在这里看到的一段代码http://guides.ruby.tw/ruby/strings.html,guess.chop!有什么在这里是什么意思。没理解

# 把程式儲存為 guess.rb
words = ['foobar', 'baz', 'quux']
secret = words[rand(3)]

print "guess?"
while guess = STDIN.gets
  #这个chop!是什么意思
  guess.chop!
  if guess == secret
    puts "You win!"
    break
  else
    puts "Sorry, you lose."
  end
  print "guess?"
end
puts "The word was " + secret + "."

http://www.ruby-doc.org/core-1.9.3/String.html#method-i-chop

Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn’t end in a record separator.

STDIN.gets 在用户输入后最后会有换行符,把换行符去掉

教程下面有说 現在,先別太在意這個程式碼的細節。 :)

#1 楼 @kenshin54 恩,知道这个定义,本来觉得应该没有什么需要 chop 的,再调试了下,它的意思是chop 掉最后的那个换行符。 thanks!

#2 楼 @kenshin54 呵呵,也是刚发现

需要 登录 后方可回复, 如果你还没有账号请 注册新账号