【问题标题】:What is wrong with my if statements?我的 if 语句有什么问题?
【发布时间】:2013-10-29 11:49:13
【问题描述】:

在 Ruby 中工作,我正在努力做到这一点,因此当我输入一行输入时,它会读取它并将其与一些 if 语句匹配。

input_stream = $stdin

input_stream.each_line do |line|  

  puts line

  if line == "a"
    puts "test 1"
  end
  if line == "b"
    puts "test 2"
  end
end

但是当我运行它并输入“a”或“b”时,这是输出

a
a
b
b

它识别出我输入了 a 和 b,并将其打印回给我,但 if 语句没有按预期运行。这里有什么问题?

【问题讨论】:

    标签: ruby input io


    【解决方案1】:

    Ruby 在使用each_line 时维护换行符。最简单的解决方案是使用chomp 删除它。

    input_stream = $stdin
    
    input_stream.each_line do |line|  
      line.chomp! # The new helpful line
    
      puts line
    
      if line == "a"
        puts "test 1"
      end
      if line == "b"
        puts "test 2"
      end
    end
    

    【讨论】:

      【解决方案2】:

      因为行的末尾有 \n 字符,如果你这样写,它会起作用:

      input_stream = $stdin
      
      input_stream.each_line do |line|  
      
        puts line
      
        if line.chomp == "a"
          puts "test 1"
        end
        if line.chomp == "b"
          puts "test 2"
        end
      end
      

      【讨论】:

      • 那 \n 不是一个符号,它是一个字符。在 Ruby 中,符号看起来像 :symbol,符号名称前面有冒号。在作为键的哈希中,我们可以方便地创建像 key: value 这样的符号,在这种情况下,值将是一个变量(或者可能是一个方法调用),其余的是 Ruby 历史记录。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多