Ruby: Case Using Object

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

class Foo

  def bar
    1
  end

  def baz
    ...
  end

end

What I would like 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 evaluate the return of methods to the case object. Is such a structure possible? I could not understand the syntax, if so ...

+5
source share
4 answers

FWIW, you do not need to pass the object to the 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 a gegg.

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

+9
source

case .. when, === when, foo ===. , :

case foo
when 1 then "something"
when 2 then "something else"
when 3 then "another thing"
end

1 === foo, 2 === foo, 3 === foo, .

case .. when Procs when. Ruby, 1.9, proc === x proc.call(x). :

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

, foo Procs, . , , ifs :

if foo.bar == 1
  "something"
elsif foo.bar == 2
  "something else"
elsif foo.baz == 3
  "another thing"
end
+6

, . , - :

string = Foo.new.instance_eval do
  if bar==1 then "something"
  elsif bar==2 then "something else"
  elsif baz==3 then "another thing"
  end
end

, , , , . , DSL, - .

+4
source

For another scenario where you want to check the value of the true method 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"
0
source

All Articles