有没有办法定义一个可以被强制转换为 String 或 Fixnum 或 Float 的对象?这用于收集值并使用它们评估一组受限制的简单表达式的系统。
我试过:
class EmptyValue < Numeric
def to_s; ''; end
def to_str; ''; end
def to_i; 0; end
def to_int; 0; end
def to_f; 0.0; end
end
但这对
来说是失败的1 + e
TypeError: EmptyValue can't be coerced into Fixnum
最佳答案
再深入一点,这对我所有的用例都有效:
class EmptyValue < Numeric
def to_s; ''; end
def to_str; ''; end
def to_i; 0; end
def to_int; 0; end
def to_f; 0.0; end
def +(other)
case other
when String
to_s + other
when Fixnum
to_i + other
when Float
to_f + other
end
end
end
关于ruby - 可以强制转换为 String、Fixnum 或 Float 的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17054812/