有没有办法从ruby case语句中访问表达式?
我想从then子句中访问case语句表达式,即有没有办法从ruby case语句中访问表达式?,ruby,case,Ruby,Case,我想从then子句中访问case语句表达式,即 food = "cheese" case food when "dip" then "carrot sticks" when "cheese" then "#{expr} crackers" else "mayo" end 在这种情况下,expr是食品的当前价值。在这种情况下,我知道,我可以简单地访问变量food,但是在某些情况下,可能无法再访问该值(array.shift等)。除了将expr移出到局部变量中然后访问它之外,还有没有直接访问c
food = "cheese"
case food
when "dip" then "carrot sticks"
when "cheese" then "#{expr} crackers"
else
"mayo"
end
在这种情况下,expr是食品的当前价值。在这种情况下,我知道,我可以简单地访问变量food,但是在某些情况下,可能无法再访问该值(array.shift等)。除了将expr移出到局部变量中然后访问它之外,还有没有直接访问cases expr值的方法
罗亚
p、 我知道这个具体的例子并不重要,只是一个简单的例子而已。这是一个混乱的例子,但似乎很有效
food = "cheese"
case food
when ( choice = "dip" ): "carrot sticks"
when (choice = "cheese" ): "#{ choice } crackers"
else
"mayo"
end
那么:
food = "cheese"
x = case food
when "dip" then "carrot sticks"
when /(cheese|cream)/ then "#{ $1 } crackers"
else
"mayo"
end
puts x # => cheese crackers
嗯,我想这确实是一种“方式”,它最终被分配到了一个全球组织:it’非常感谢你的煽动
x
这里可以是任何范围的变量。仅当您将其指定给全局时,它才会指定给全局。在ruby中,case状态返回一个值。您只需选择在您选择的变量中捕获该值。这似乎只适用于使用匹配的情况,然后匹配的结果是$1。如果您不使用匹配,那么Wayne Conrad的答案会更好、更清晰。@Josh:不幸的是,在Wayne的解决方案中,值
没有本地化(在案例/结束
中),因此会出现潜在的变量污染问题。我个人更喜欢我的方法,似乎还记得它也曾在编程Ruby
一书中使用过。@WayneConrad-x
不是由case
表达式(block)创建或使用的。这只是为了澄清@Roja的问题和示例代码。如果删除了x
,则案例仍然有效:)
#!/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)