On 10/31/2009 10:10 PM, Braxton Beyer wrote:
> I want to be able to do something like this:
>
> 1000.case when 100 then "string1" when 110 then "string2" else "Unknown"
> end
Here's a completely different but probably more efficient variant:
irb(main):004:0> h=Hash.new("Unknown").merge(100=>"string1",110=>"string2")
=> {100=>"string1", 110=>"string2"}
irb(main):005:0> h[100]
=> "string1"
irb(main):006:0> h[110]
=> "string2"
irb(main):007:0> h[120]
=> "Unknown"
irb(main):008:0>
> I have an app that allows an admin to enter a filter that is ruby code.
> The filter code is then applied directly to a variable. Is there a way
> to apply a case statement such as the one above
Given eval anything is possible with code entered via the terminal. You
could do
irb(main):010:0> val = 100
=> 100
irb(main):011:0> input = "case when 110 then 'foo' else 'bar' end"
=> "case when 110 then 'foo' else 'bar' end"
irb(main):012:0> prepared = input.gsub(/case/, '\\& val')
=> "case val when 110 then 'foo' else 'bar' end"
irb(main):013:0> eval(prepared)
=> "bar"
Although that approach would need to be more complex for other
scenarios. And you need to be aware of the security implications of
using eval.
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/