Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

case

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.

like image 679
Roja Buck Avatar asked Jan 25 '10 15:01

Roja Buck


1 Answers

#!/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)
like image 99
Wayne Conrad Avatar answered Sep 28 '22 17:09

Wayne Conrad