ruby - 万一我能回忆起“案例”吗?
问题描述
我想回忆这个案例,直到用户写 a 或 b。我不想特别使用“案例”。
我只想从用户那里得到输入,而不是得到其他东西。如果他写别的东西,他应该一直写到写完a或b为止。
str = gets.chomp.to_s
case str
when "a"
print "nice a"
when "b"
puts "nice b"
else
puts "please do it again"
end
class person
attr_accessor :name , :surname #and other attributes
end
#There will be a method here and it will run when the program is opened.
#The method will create the first object as soon as the program is opened.
#The new object that the user will enter will actually be the 2nd object.
puts "What do you want to do?
add
list
out"
process = gets.chomp.to_s
case process
when "add"
#in here user will add new objects of my class
when "list"
#in here user will show my objects
when "out"
puts "Have a nice day"
else
puts "please do it again"
end
事实上,如果你看它,很多动作都会因为用户输入正确的输入而被执行。我想讲的在这个例子中更详细。根据用户的输入,会有调用方法、添加对象等动作。
我在我的电脑上编写了大部分代码。但我仍然无法解决我的第一个问题。
解决方案
while
当你使用某种循环时,“我只想做某事直到发生其他事情” 。
你可以这样做:
while true
str = gets.chomp
break unless str == 'a' || str == 'b'
puts "please do it again"
end
您还可以使用loop do
:
loop do
str = gets.chomp
break unless ['a', 'b'].include?(str)
puts "please do it again"
end
puts "Nice #{str}."
Rubyists 往往更loop do
喜欢while true
. 他们做的事情几乎一样。
还有一件事。有一种更简单的方法可以写出字符串数组:
loop do
str = gets.chomp
break unless %w(a b).include?(str)
puts "please do it again"
end
puts "Nice #{str}."
它看起来并不简单,但是如果你有 10 个字符串,那么当你不必使用所有这些引号时,输入肯定会更快。
正如您的直觉告诉您的那样,您根本不需要使用该case
语句。就像试图用大锤杀死跳蚤一样。进行检查的最简洁方法是检查输入字符是否包含在所需字符的数组中。
推荐阅读
- grafana - 使用 Helm Charts 持久化 Grafana
- java - 用于测试 IBM-MQ 的服务器和客户端应用程序中的问题
- reactjs - Material UI 自定义样式不适用于组件
- xml - 使用 SAXON 和 XSLT 合并 XML 文件
- python - 如何将熊猫数据框插入 SQL 的 IN 运算符
- .htaccess - 如何将 roodomain/addondomain url 重定向到 addondomain
- flutter - 如何在 2.5 中导入 csv 文件?
- python - 根据键在数据帧之间减去多列
- powershell - Powershell 中选择对象的更高效替代方案
- android - algolia kotlin 客户端无法在 android 中运行