6

我想从 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 的值?

罗亚

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

4

3 回答 3

9
#!/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)
于 2010-01-25T17:36:24.547 回答
3

怎么样:

food = "cheese"

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

puts x  # => cheese crackers
于 2010-01-25T16:23:49.377 回答
-1

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

food = "cheese"
case food
when ( choice = "dip" ): "carrot sticks"
when (choice = "cheese" ): "#{ choice } crackers"
else
  "mayo"
end
于 2010-01-25T15:13:49.387 回答