从 switch 语句获取控制变量

发布于 2024-11-14 08:42:12 字数 246 浏览 1 评论 0原文

ruby 中 switch 语句的基本语法是

case expression
  when condition1
    statements1
  when condition2
    statements2
  else
    statements
end

有没有办法在语句中获取控制表达式值?

意思是,是否有一些变量存储可以直接使用的表达式值 - 并且表达式不需要在语句体中再次调用?

the basic syntax of switch statement in ruby is

case expression
  when condition1
    statements1
  when condition2
    statements2
  else
    statements
end

Is there a way to get control expression value in statements?

Means, is there some variable which stores expression value which can be used directly - and expression need not be called again in statements body?

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

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

发布评论

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

评论(3

时光无声 2024-11-21 08:42:12

没有魔法变量。使用普通变量并不麻烦:

case a = expensive_method
  when condition1
    puts "#{a} meets condition 1"
  when condition2
    puts "#{a} meets condition 2"
end

There is no magic variable. It's no trouble to use an ordinary variable:

case a = expensive_method
  when condition1
    puts "#{a} meets condition 1"
  when condition2
    puts "#{a} meets condition 2"
end
一曲爱恨情仇 2024-11-21 08:42:12

不,没有。但你可以这样做:

case var = expression
when condition1
  statements1
when condition2
  statements2 # use var whenever you like..
else
  statements
end

No, there isn't. But you can just do this:

case var = expression
when condition1
  statements1
when condition2
  statements2 # use var whenever you like..
else
  statements
end
吃兔兔 2024-11-21 08:42:12

自己内联分配变量很简单:

case result = expression
when condition1
  result + 1
when condition2
  result + 2
else
  result
end

It's straightforward to assign the variable yourself inline:

case result = expression
when condition1
  result + 1
when condition2
  result + 2
else
  result
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文