有人能举例说明如何在Ruby中使用switch case for variable吗?

推荐答案

我想你指的是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

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

编辑

也许每个人都知道在这种情况下什么是有用的.

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}"

Ruby相关问答推荐

ruby 3.1:使用方法(:名称)简化代码莫名其妙地失败

鲁比.METHOD_MISSING+SEND对于带有命名参数的混合参数失败

定义Struct时如何指定成员的类型?

Ruby:这两种混入模块方法是否等效?

碰撞检测测试中对象的 Nil 类

Rb:仅通过在 Ruby 中的类上添加 each 方法,可枚举模块是如何工作的?

删除带括号的子表达式

整数除以负数

数组到哈希:字数

用于 ruby​​ gems 的新 10.9 OSX 的命令行工具?

根据另一个数组的元素对数组进行排序

Ruby 多维数组

如何删除Ruby中数组中满足条件的所有元素?

在 Ruby 中将散列扁平化为字符串

Ruby,生成随机十六进制 colored颜色

测试变量是否等于两个值之一

如何将多个元素添加到数组中?

Ruby - Array#<< 和 Array#push 之间的区别

Ruby on Rails switch

如何在没有 RVM 的 Ubuntu 上安装 Ruby 2