ruby - Why is this case when not working properly? -


  if ( item::class == rpg::weapon )     print "yup"   end   case item::class   when rpg::item     type = 0   when rpg::weapon     type = 1   when rpg::armor     type = 2   else     type = 10   end 

i'm new ruby. if statement runs fine , prints "yup", case statement isn't working , sets type 10. blind or what?

module#=== tests if argument instance of self. item.class can never instance of class, in particular, never instance of either rpg::weapon or rpg::armor, therefore none of when branches ever match , else branch.

by way: using namespace resolution operator :: message sends instead of message sending operator . extremely un-idiomatic , confusing (and won't work methods name starts uppercase character). in fact, believe matz considers adding feature ruby mistake.

note case expression, in fact, everything in ruby expression.

i write code follows:

type = case item   when rpg::item     0   when rpg::weapon     1   when rpg::armor     2   else     10 end 

however, in general, conditionals code smell. ruby object-oriented language, polymorphism (i.e. method dispatching based on type of self) all conditional need! in fact, in example, manually examining class of item in order determine type, exactly method dispatch anyway! personally, refactor code this:

class rpg::item   def type     0   end end  class rpg::weapon   def type     1   end end  class rpg::armor   def type     2   end end  class rpg::object # or whatever baseclass   def type     10   end end 

now when add new kind of game object, don't have modify existing code adding new branch case expression. add new class, without needing modify existing code.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -