如何在Ruby中编写switch语句?
当前回答
我们可以为多个条件编写switch语句。
例如
x = 22
CASE x
WHEN 0..14 THEN puts "#{x} is less than 15"
WHEN 15 THEN puts "#{x} equals 15"
WHEN 15 THEN puts "#{x} equals 15"
WHEN 15..20 THEN puts "#{x} is greater than 15"
ELSE puts "Not in the range, value #{x} "
END
其他回答
如果您需要“小于”或“大于”:
case x
when 1..5
"It's between 1 and 5"
when 6
"It's 6"
when 7..1.0/0
"It's equal or greater than 7"
when -1.0/0..0
"It's equal or less than 0"
end
1.0/0等于Float::INFINITY,因此您可以使用自己喜欢的。
在Ruby 2.6之后,您可以使用Endless Ranges,在Ruby 2.7之后,您还可以使用Beginless Ranges,例如:
case x
when 1..5
"It's between 1 and 5"
when 6
"It's 6"
when (7..)
"It's equal or greater than 7"
when (..0)
"It's equal or less than 0"
end
$age = 5
case $age
when 0 .. 2
puts "baby"
when 3 .. 6
puts "little child"
when 7 .. 12
puts "child"
when 13 .. 18
puts "youth"
else
puts "adult"
end
有关更多信息,请参阅“Ruby-if…else,case,除非”。
puts "Recommend me a language to learn?"
input = gets.chomp.downcase.to_s
case input
when 'ruby'
puts "Learn Ruby"
when 'python'
puts "Learn Python"
when 'java'
puts "Learn Java"
when 'php'
puts "Learn PHP"
else
"Go to Sleep!"
end
你可以用更自然的方式这样做,
case expression
when condtion1
function
when condition2
function
else
function
end
多值时和无值情况:
print "Enter your grade: "
grade = gets.chomp
case grade
when "A", "B"
puts 'You pretty smart!'
when "C", "D"
puts 'You pretty dumb!!'
else
puts "You can't even use a computer!"
end
这里有一个正则表达式解决方案:
print "Enter a string: "
some_string = gets.chomp
case
when some_string.match(/\d/)
puts 'String has numbers'
when some_string.match(/[a-zA-Z]/)
puts 'String has letters'
else
puts 'String has no numbers or letters'
end
推荐文章
- 我如何在Ruby中解析YAML文件?
- Rails中的OO设计:在哪里放置东西
- 给定一个类,查看实例是否有方法(Ruby)
- 在日历应用程序中建模重复事件的最佳方法是什么?
- 如何创建一个私有类方法?
- 无法安装pg gem
- 双* (splat)操作符做什么
- 如何使用Ruby on Rails进行HTTP请求?
- 如何从rake任务中提前返回?
- 什么&。(&点)在Ruby中是什么意思?
- 是什么阻碍了Ruby和Python获得V8的Javascript速度?
- 如何使用开关案件'或'在PHP
- 运行pod设置给我“坏的解释器:没有这样的文件或目录”错误
- 在Ubuntu上安装sqlite3-ruby错误
- Ruby有什么Python没有的,反之亦然?