Ruby on Rails 开关

发布于 2024-11-19 02:02:05 字数 52 浏览 0 评论 0原文

有人可以提供一个关于如何在 Ruby 中使用 switch case 来表示变量的示例吗?

Can someone provide an example on how to use switch case in Ruby for variable?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终止放荡 2024-11-26 02:02:05

我假设你指的是案例/时间。

case a_variable # a_variable is the variable we want to compare
when 1    #compare to 1
  puts "it was 1" 
when 2    #compare to 2
  puts "it was 2"
else
  puts "it was something else"
end

puts case a_variable
when 1
  "it was 1"
when 2
  "it was 2"
else
  "it was something else"
end

编辑

可能不是每个人都知道但非常有用的是您可以在 case 语句中使用正则表达式。

foo = "1Aheppsdf"

what = case foo
when /^[0-9]/
  "Begins with a number"
when /^[a-zA-Z]/
  "Begins with a letter"
else
  "Begins with something else"
end
puts "String: #{what}"

I assume you refer to case/when.

case a_variable # a_variable is the variable we want to compare
when 1    #compare to 1
  puts "it was 1" 
when 2    #compare to 2
  puts "it was 2"
else
  puts "it was something else"
end

or

puts case a_variable
when 1
  "it was 1"
when 2
  "it was 2"
else
  "it was something else"
end

EDIT

Something that maybe not everyone knows about but what can be very useful is that you can use regexps in a case statement.

foo = "1Aheppsdf"

what = case foo
when /^[0-9]/
  "Begins with a number"
when /^[a-zA-Z]/
  "Begins with a letter"
else
  "Begins with something else"
end
puts "String: #{what}"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文