有什么方法可以从 ruby​​ case 语句中访问表达式吗?

发布于 2024-08-19 06:25:15 字数 365 浏览 5 评论 0原文

我想从 then 子句中访问 c​​ase 语句表达式,即

food = "cheese"
case food
when "dip" then "carrot sticks"
when "cheese" then "#{expr} crackers"
else
  "mayo"
end

在本例中 expr 是食物的当前值。在这种情况下,我知道,我可以简单地访问变量 food,但是在某些情况下,该值可能不再可访问(array.shift 等)。除了将 expr 移出到局部变量中然后访问它之外,是否有其他方法可以直接访问 case expr 的值?

罗哈

附注我知道这个具体的例子是微不足道的,它只是一个示例场景。

I would like to access the case statements expression from within a then clause i.e.

food = "cheese"
case food
when "dip" then "carrot sticks"
when "cheese" then "#{expr} crackers"
else
  "mayo"
end

where in this case expr would be the current value of food. In this case I know, I could simply access the variable food, however there may be cases where the value is no longer accessible (array.shift etc..). Other than moving the expr out into a local variable and then accessing it, is there a way of directly accessing the value of the cases expr?

Roja

p.s. I know that this specific example is trivial its mealy an example scenario.

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

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

发布评论

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

评论(3

猫烠⑼条掵仅有一顆心 2024-08-26 06:25:15
#!/usr/bin/ruby1.8

a = [1, 2, 3]
case value = a.shift
when 1
  puts "one (#{value})"
when 2
  puts "two (#{value})"
end

# => one (1)
#!/usr/bin/ruby1.8

a = [1, 2, 3]
case value = a.shift
when 1
  puts "one (#{value})"
when 2
  puts "two (#{value})"
end

# => one (1)
听你说爱我 2024-08-26 06:25:15

怎么样:

food = "cheese"

x = case food
  when "dip" then "carrot sticks"
  when /(cheese|cream)/ then "#{ $1 } crackers"
else
  "mayo"
end

puts x  # => cheese crackers

How about:

food = "cheese"

x = case food
  when "dip" then "carrot sticks"
  when /(cheese|cream)/ then "#{ $1 } crackers"
else
  "mayo"
end

puts x  # => cheese crackers
七月上 2024-08-26 06:25:15

这很混乱,但似乎有效......

food = "cheese"
case food
when ( choice = "dip" ): "carrot sticks"
when (choice = "cheese" ): "#{ choice } crackers"
else
  "mayo"
end

This is messy but seems like it works...

food = "cheese"
case food
when ( choice = "dip" ): "carrot sticks"
when (choice = "cheese" ): "#{ choice } crackers"
else
  "mayo"
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文