tags:

views:

73

answers:

3

Hi All,

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.

A: 

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
Farrel
`case food= "cheese"`
johannes
+2  A: 

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

/I3az/

draegtun
Hmm i am thinking that this is indeed the "way" shame it ends up being assigned to a global :S Much appreciate the incite!
roja
`x` here can be a variable of any scope. It only assigns to a global if you assign it to a global. This everything in ruby, the case state state returns a value. You simply and optionally capture that value in a variable of your choosing.
Squeegy
+1  A: 
#!/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)
Wayne Conrad