如何使用“获取"和“gets.chomp"在红宝石 [英] How to use "gets" and "gets.chomp" in Ruby

查看:37
本文介绍了如何使用“获取"和“gets.chomp"在红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到 gets 创建一个新行并要求用户输入一些东西,而 gets.chomp 做同样的事情,只是它不创建一个新行.gets 必须返回一个对象,因此您可以对其调用方法,对吗?如果是这样,让 gets 返回的对象命名为 tmp,然后你可以调用 tmpchomp 方法.但是在 gets 返回 tmp 之前,它应该在屏幕上打印一个新行.那么 chomp 做了什么?在 gets 创建新行之后,它会删除新行吗?

I learned that gets creates a new line and asks the user to input something, and gets.chomp does the same thing except that it does not create a new line. gets must return an object, so you can call a method on it, right? If so, lets name that object returned by gets as tmp, then you can call the chomp method of tmp. But before gets returns tmp, it should print a new line on the screen. So what does chomp do? Does it remove the new line after the gets created it?

另一种重新阐述我的问题的方法是:当我调用 gets.chomp 时是否执行了以下操作?

Another way to re-expound my question is: Are the following actions performed when I call gets.chomp?

  1. gets 打印一个新行
  2. gets 返回 tmp
  3. tmp.chomp 删除新行
  4. 用户输入
  1. gets prints a new line
  2. gets returns tmp
  3. tmp.chomp removes the new line
  4. User input

这是正确的顺序吗?

推荐答案

gets 允许用户输入一行并将其作为值返回给您的程序.此值包括尾随换行符.如果随后对该值调用 chomp,则此换行符将被切断.所以不,你有什么是不正确的,它应该是:

gets lets the user input a line and returns it as a value to your program. This value includes the trailing line break. If you then call chomp on that value, this line break is cut off. So no, what you have there is incorrect, it should rather be:

  1. gets gets 一行文本,包括 末尾的换行符.
    • 用户输入
  1. gets gets a line of text, including a line break at the end.
    • This is the user input

您在屏幕上看到文本行的事实只是因为您首先在那里输入了它.gets 不会神奇地抑制您输入的内容的输出.

The fact that you see the line of text on the screen is only because you entered it there in the first place. gets does not magically suppress output of things you entered.

这篇关于如何使用“获取"和“gets.chomp"在红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆