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

mayday · January 18, 2013 · Last by mayday replied at January 18, 2013 · 4154 hits

在这里看到的一段代码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 呵呵,也是刚发现

You need to Sign in before reply, if you don't have an account, please Sign up first.