简体   繁体   中英

Ruby special usage of CASE Statement

I've got some piece of code:

variable = ...
case variable
when ~:new
  ':new method!'
when ~:lenght
  ':size method!'
end

For o = [] it should go to size case and return ':size method!' For o = String should return ':new method' And this part I know how to implement(my solution below) But it should work with any kind of object. And this part I don't know how to implement. I don't know what is wrong in my code and is it correct? My code:

module AbstractClass
  def new; false end;
  def size; false end;
end

class Class
  include AbstractClass
end

class Array
  include AbstractClass
  def size; true end;
end

class String
  include AbstractClass
  def new; true end;
end

class Symbol
  include AbstractClass
  alias ~ to_proc
end

Thank you for help!

I know what you did here :) I can give you a hint.

Important thing is to understand how case statements work in Ruby. If you have following code:

case variable
when 1
  # do stuff
when "foo"
  # do other stuff
end

Ruby is actually calling === method on those values:

1 === variable
"foo" === variable

Or

1.===(variable)
"foo".===(variable)

The order is important here. And since those are just methods you can override them for any object to provide some custom behavior related to comparing two objects.

def MyClass
  def ===(other)
    # do my own comparison
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM