Ruby: Case using object

Viewed 3751

Is there a way to implicitly call methods on the object of a case statement? IE:

class Foo

  def bar
    1
  end

  def baz
    ...
  end

end

What I'd like to be able to do is something like this...

foo = Foo.new
case foo
when .bar==1 then "something"
when .bar==2 then "something else"
when .baz==3 then "another thing"
end

... where the "when" statements are evaluating the return of methods on the case object. Is some structure like this possible? I haven't been able to figure out the syntax if so...

4 Answers

For different scenario where you want to test truthy method value of an object

class Foo
  def approved?
    false
  end

  def pending?
    true
  end
end

foo = Foo.new
case foo
when :approved?.to_proc
  puts 'Green'
when :pending?.to_proc
  puts 'Amber'
else
  puts 'Grey'
end

# This will output:  "Amber"
Related