ruby 从命令行读取文本

最常见的方式就是使用内置的get 方法,这个方法可以从命令行读取用户的输入,并在默认的情况下把读入的文本赋值给预定义变量$_.

但是get方法会保留用户在输入字符串末尾所加的换行符,当用户在输入的字符串结尾输入了句号,并按了回车,得到的是stop 。

ruby中提供了另外一个内置的方法chomp,它会除去$_后面的换行符。

    print "please enter anything:"  
    gets  
    chomp  
    puts "The input is #{$_}"  

 

 
用户的输入可以赋值给一个变量并来替换$_,但是删除末尾的空行就有问题,因为chmop只能对$_操作,而其不能指定变量为 chmop,这是代码就要这样写
Ruby代码  收藏代码

    print "please enter the temperature:"  
    temp=gets  
      
    $_=temp  
      
    chomp  
      
    temp=$_  
      
    puts "The temperature is #{$_}" 

引用链接:http://chenhua-1984.iteye.com/blog/528129

原文地址:https://www.cnblogs.com/dami520/p/3225714.html