2

两天前我才开始研究 Ruby 语言,并很快了解到我过于拘泥于 C 派生语言的思维方式......我正在尝试对字符串进行比较:

def menu_listen
    action = gets
    while !(action.eql?("up")) && !(action.eql?("down")) && !(action.eql?("close")) do
        puts "'#{action}' is not a valid command at this time."
        action = gets
    end
    return action
end

...之前是这样写的:

def main_listen
    action = gets
    while action != "up" && action != "down" && action != "close" do
        puts "'#{action}' is not a valid command at this time."
        action = gets
    end
    return action
end

我在这个网站上读到 thisString.eql?(thatString) 与 thisString == thatString 相同,因为两者都不起作用。我在命令提示符中输入的任何输入都不会通过 while 循环并给我这个作为响应:

'down
' is not a valid command at this time.

那么这是否意味着按下回车键也存储为命令提示符输入的新行?谁能告诉我如何实现这一点,以便字符串比较正常工作?

4

3 回答 3

4

gets也接受 eol 字符,所以使用gets.chomp只接受实际的字符串。该chomp方法删除您的回车以及换行符。

就字符串比较而言,它更像是比较您的输入是否存在于预定义字符串数组中,而不是链接&&and eql?,例如:

while not %w(up down close).include? action do

这比链接更干净,也更容易修改。

于 2012-11-16T00:04:31.887 回答
2
def menu_listen
  until r = (['up', 'down', 'close'] & [t = gets.strip]).first 
    puts "#{t} is not a valid command"
  end
  r
end
于 2012-11-16T00:17:26.260 回答
0

您所需要的只是一个String#chomp方法,该方法从字符串末尾删除分隔符。

    def menu_listen
      while 1 do
        action = gets.chomp
        return action if %w(down up close).include? action.downcase
        puts "#{action}' is not a valid command at this time."
      end
    end
于 2012-11-16T00:17:11.670 回答