有没有办法从ruby case语句中访问表达式?

时间:2010-01-25 15:09:02

标签: ruby case

我想从then子句中访问case语句表达式,即

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

在这种情况下,expr将是食物的当前值。在这种情况下,我知道,我可以简单地访问变量食物,但是可能存在值不再可访问的情况(array.shift等..)。除了将expr移到局部变量然后访问它之外,有没有办法直接访问案例expr的值?

Roja的

P.S。我知道这个具体的例子很简单,只是一个例子。

3 个答案:

答案 0 :(得分:8)

#!/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)

答案 1 :(得分:3)

怎么样:

food = "cheese"

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

puts x  # => cheese crackers

答案 2 :(得分:-1)

这很乱,但看起来很有效......

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