用户画像数据从哪获取
To make the program to interact with user, a program usually needs input from the users. To do this, we can use gets
method. gets
function takes input from the keyboard in string format and stores the value in the variables.
为了使程序与用户交互,程序通常需要来自用户的输入。 为此,我们可以使用gets
方法。 gets
函数从键盘以字符串格式获取输入并将值存储在变量中。
name = gets
This statement takes a string input from the user and stores it in the variable called name.
该语句从用户那里获取一个字符串输入,并将其存储在名为name的变量中。
It also appends a \n
new line character at the end of the input entered by the user.
它还在用户输入的输入末尾附加\n
新行字符。
So, when you type the variable name, it displays what is stored in it. When you display using print
function, it displays the text entered by the user along with a new line. To remove the newline, you can use a function called chomp
. The following statement removes the newline from the input entered by the user.
因此,当您键入变量名称时,它将显示存储在其中的内容。 使用print
功能显示时,它将显示用户输入的文本以及新行。 要删除换行符,可以使用一个称为chomp
的函数。 以下语句从用户输入的输入中删除换行符。
print name.chomp
The following code performs addition of two whole numbers with the numbers provided by the user:
以下代码执行两个整数与用户提供的数字的加法运算:
number1 = gets
number2 = gets
(Integer)number1 + Integer(number2)
Integer()
part of the code looks tricky for you now.
现在,代码的Integer()
部分对您来说很棘手。
As mentioned before, gets
method gets input in string format. So, conversion to whole number is required before arithmatic operations could be perfomed on the data. This can be done using Integer()
function.
如前所述, gets
方法以字符串格式获取输入。 因此,在对数据进行算术运算之前,需要转换为整数。 这可以使用Integer()
函数完成。
If you don't convert those variables into integer, it will concatenate the two string instead of performing arithmatic addition,. Do you remember concatenating two strings which we have seen earlier in Chapter 1? Likewise, to add two decimal numbers, look at the following code:
如果不将这些变量转换为整数,它将连接两个字符串而不是执行算术加法。 您还记得将第一章前面看到的两个字符串串联起来吗? 同样,要添加两个十进制数字,请查看以下代码:
num1 = gets
num2 = gets
float(num1) + float(num2)
NOTE: float()
method is used to convert data into decimal format. If the conversion is not done, it simply performs the concatenation operation as said before.
注意: float()
方法用于将数据转换为十进制格式。 如果未完成转换,则仅执行如前所述的串联操作。
翻译自: https://www.studytonight.com/ruby/getting-user-input-ruby
用户画像数据从哪获取