0

我只是在学习 Ruby,我对以下内容有点困惑:

#!/usr/bin/env ruby

while line = gets
  if line == 'x'
    puts 'You pressed x'
  end
end

如果输入 x,它似乎不会打印任何内容。我做的比较正确吗?

4

2 回答 2

5

gets返回输入的文本以及换行符。试试这个:

while line = gets.chomp
  # the rest is the same
end

String#chomp从字符串中删除此类字符 ( \n, \r, \r\n)。

于 2013-04-29T19:56:54.017 回答
1

当您键入 x 然后按enter您正在添加\n和/或\r.

要解决此问题,您必须比较

if line.chomp == 'x'

你的循环应该可以工作并打印出“你按下了 x”

于 2013-04-29T19:59:36.107 回答