问题
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
回答1:
The comparison in the case statement is done with the ===
- also called the case equality operator. For classes like String
or Fixnum
it defined as to test 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
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, what makes the method a bit shorter:
def div(arg)
case arg
when String
[arg, arg.size]
when Fixnum
arg
end
end
回答2:
I think I'd prefer:
def div(arg)
return arg if arg.is_a? Fixnum
[arg, arg.size] if arg.is_a? String
end
来源:https://stackoverflow.com/questions/43957892/ruby-case-class-check