2

How can I get the following code to work (I want to decide upon an action based on the class of the arg):

def div arg material = case arg.class when String [arg, arg.size] when Fixnum arg end material end 

2 Answers 2

4

The comparison in the case statement is done with the === - also called the case equality operator. For classes like String or Fixnum it is defined as testing if the object is an instance of that class. Therefore instead of a class just pass the instance to the comparison by removing the .class method call:

def div arg material = case arg when String [arg, arg.size] when Fixnum arg end material end 

Additional note: In your example, you assign the result of the case block to a local variable material which you return right after the block. This is unnecessary and you can return the result of the block immediately, which makes the method a bit shorter:

def div(arg) case arg when String [arg, arg.size] when Fixnum arg end end 
Sign up to request clarification or add additional context in comments.

2 Comments

I suggest you provide an explanation.
Sehr schön! :-)
0

I think I'd prefer:

def div(arg) return arg if arg.is_a? Fixnum [arg, arg.size] if arg.is_a? String end 

1 Comment

With this version you may get an NoMethodError-exception (e.g. with div(1.1).