开发者

Is there any way to access the expression from within a ruby case statement?

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 ou开发者_运维技巧t 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.


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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜