6

then句内からcaseステートメント式にアクセスしたい。

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

この場合、exprは食品の現在の価値になります。この場合、私は簡単に可変食品にアクセスできますが、値にアクセスできなくなる場合があります(array.shiftなど)。exprをローカル変数に移動してアクセスする以外に、cases 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 に答える