在 ruby 中使用 get 接受用户输入
在 ruby 中构建命令行 (cli) 应用程序时,一个常见的功能是接收来自用户的输入,包括用户名或是/否
响应。这就是 gets
关键字有用的地方。
本篇文章将展示如何构建一个非常简单的 cli 程序,该程序允许用户输入他们的名字并使用他们输入的名字问候他们。
示例代码:
puts "hi, welcome to my app."
puts "enter your name to get started: "
name = gets
puts "hello #{name}, nice to have you here"
输出:
hi, welcome to my app.
enter your name to get started:
以上是我运行代码后得到的输出。此时,程序要求我输入我的名字。这就是 gets
所做的;它创建一个提示并等待用户输入。
下面是我输入我的名字为 john
并按 enter 键后得到的完整输出。
hi, welcome to my app.
enter your name to get started:
john
hello john
, nice to have you here
你一定已经注意到上面的输出中有一些奇怪的东西。为什么打招呼 hello john, nice to have you here
在 john
之后中断?要了解实际情况,请检查变量 name
。
示例代码:
puts "hi, welcome to my app."
puts "enter your name to get started: "
name = gets
puts name.inspect
puts "hello #{name}, nice to have you here"
输出:
hi, welcome to my app.
enter your name to get started:
john
"john\n"
hello john
, nice to have you here
以上是我输入 john
作为我的名字后得到的完整输出。你可以看到 name
变量显示为 john\n
。
这就是 gets
的行为方式;它会自动将\n
附加到它作为用户输入接收到的任何值上,这称为换行符,每当它出现在文本中时,这意味着文本应该在该点中断,并在新行上继续。
解决此问题的一个好方法是使用 chomp
方法,该方法删除任何尾随特殊字符,不仅是换行符 (\n
),还包括回车符 (\r
)。
示例代码:
puts "hi, welcome to my app."
puts "enter your name to get started: "
name = gets.chomp
puts "hello #{name}, nice to have you here"
输出:
hi, welcome to my app.
enter your name to get started:
john
hello john, nice to have you here
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
发布时间:2024/02/05 浏览次数:181 分类:编程语言
-
本文演示了 ruby 中注入方法的不同用途。
发布时间:2023/03/21 浏览次数:240 分类:编程语言
-
本文介绍了在 ruby 程序中调用 shell 命令的各种方法。
发布时间:2023/03/21 浏览次数:86 分类:编程语言
-
简要讨论 ruby 中的模式匹配运算符及其使用方式。
发布时间:2023/03/21 浏览次数:89 分类:编程语言
-
本教程说明了如何在 ruby 中使用安全导航。
发布时间:2023/03/21 浏览次数:189 分类:编程语言
-
本文展示了如何在 ruby 中编写一行 if 语句