在编程中,我们经常需要用户提供一些数据。Ruby 使用 gets
方法(通常与 chomp
方法结合使用)从用户那里获取输入。
以下是获取 Ruby 用户输入的快速示例。您可以阅读本教程的其余部分以了解更多信息。
示例
# Prompt the user for input
print "Enter your name: "
# Get user input
name = gets.chomp
# Print the input
puts "Welcome, #{name}!"
# Output:
# Enter your name: Marilyn
# Welcome, Marilyn!
在这里,我们使用 gets
将用户输入存储在 name
变量中,并使用 chomp
删除了末尾的换行符。然后,我们打印了该变量。
使用 gets 获取用户输入
如您所知,我们使用 gets
方法获取用户输入。让我们看看仅使用它而不使用 chomp
方法会发生什么
# Prompt the user for input
print "Enter your name: "
# Get user input without chomp
name = gets
# Print the input
puts "Welcome, #{name}!"
输出
Enter your name: Marilyn Welcome, Marilyn !
将此程序与我们之前的示例进行比较。您会发现之前的程序在同一行打印了 Welcome, Marilyn!
。
但是这个程序在下一行打印了 !
。为什么?
因为 gets
方法会获取一个换行符。
您知道 **回车/换行** 键会在您的文本中插入一个新行。
因此,当用户输入数据并按下该键时,新行也会添加到输入的末尾。
接下来,我们将使用 chomp
方法来删除用户输入中的此换行符。
注意: 在 Ruby 中,换行符由换行符 "\n"
表示。因此,当用户输入 "Marilyn"
时,Ruby 会将其存储为 "Marilyn\n"
。
使用 chomp 删除换行符
Ruby 的 chomp
方法可以删除用户输入中的换行符。例如,
print "Enter your name: "
# Get user input with chomp
name = gets.chomp
print "Enter your age: "
# Get another input without chomp
age = gets
# Print the inputs
puts "Welcome, #{name}!"
puts "You are #{age} years old."
输出
Enter your name: Marilyn Enter your age: 25 Welcome, Marilyn! You are 25 years old.
在这里,我们将 gets.chomp
与 name
变量一起使用,但没有将其与 age
变量一起使用
# Get user input with chomp
name = gets.chomp
# Get another input without chomp
age = gets
结果是,age
末尾有一个换行符,但 name
没有。
让我们通过为两个输入都使用 chomp
来纠正这个问题:
print "Enter your name: "
name = gets.chomp
print "Enter your age: "
age = gets.chomp
puts "Welcome, #{name}!"
puts "You are #{age} years old."
输出
Enter your name: Marilyn Enter your age: 25 Welcome, Marilyn! You are 25 years old.
Ruby 输入是字符串
在 Ruby 中,gets
方法将用户的输入读取为字符串。例如,
puts "Enter two numbers: "
num1 = gets.chomp
num2 = gets.chomp
# Add num1 and num2
sum = num1 + num2
puts "Sum: #{sum}"
输出
Enter two numbers: 1 2 Sum: 12
在这里,我们为 num1
和 num2
提供了两个数字输入。但是当我们相加它们时,我们得到了 **12** 而不是 **3**。
这是因为我们的输入是字符串 "1"
和 "2"
。因此,使用 +
运算符“添加”两个字符串会导致这两个字符串连接在一起。
这被称为字符串连接。
# Concatenating (joining) two strings
puts "1" + "2"
# Output: 12
我们需要将输入转换为数字类型(如整数或浮点数)来解决此问题。
将输入转换为数字
我们分别使用 to_i
和 to_f
方法将字符串输入转换为整数和浮点数。
示例 1:将输入转换为整数
让我们重写之前的程序,将字符串输入转换为整数
puts "Enter two numbers: "
# Convert inputs to integers
num1 = gets.chomp.to_i
num2 = gets.chomp.to_i
sum = num1 + num2
puts "Sum: #{sum}"
输出
Enter two numbers: 1 2 Sum: 3
在这里,我们使用 to_i
在将字符串输入分配给变量之前将其转换为整数
# Convert inputs to integers
num1 = gets.chomp.to_i
num2 = gets.chomp.to_i
现在,我们终于得到了正确的总和,即 **3**。
示例 2:将输入转换为浮点数
print "Enter the price: "
price = gets.chomp.to_f
print "Enter the discount percentage: "
discount = gets.chomp.to_f
discount_amount = price * (discount / 100)
final_price = price - discount_amount
puts "Discounted Price: $#{final_price}"
puts "You saved $#{discount_amount}!"
输出
Enter the price: 560 Enter the discount percentage: 12 Discounted Price: $492.8 You saved $67.2!
在这里,我们使用 to_f
将输入转换为浮点数
price = gets.chomp.to_f
discount = gets.chomp.to_f