Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Case using object

Tags:

object

ruby

case

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...

like image 576
Andrew Avatar asked Jul 13 '11 03:07

Andrew


1 Answers

FWIW, you don't need to pass an object to a case statement in 1.8.7 at all.

foo = Foo.new()
case
when foo.bar == this then that
when foo.baz == this then that
end

I was surprised as hegg.

http://www.skorks.com/2009/08/how-a-ruby-case-statement-works-and-what-you-can-do-with-it/

like image 53
hellodally Avatar answered Oct 02 '22 22:10

hellodally