ruby - 可以强制转换为 String、Fixnum 或 Float 的对象?

标签 ruby

有没有办法定义一个可以被强制转换为 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/

相关文章:

css - 如何使用 Nokogiri 选择带冒号的 ID?

ruby - Watir Webdriver : Entering text in <p> tag within an iframe

ruby - 如何在 coffeescript 模板中访问 sinatra 类变量

ruby-on-rails - 从 ActiveRecord 对象中提取两个属性的快捷方式?

mysql - Ruby on Rails - 如何获得所有奇怪的用户

ruby - 评估值并返回二维数组中的坐标

ruby - 如何使用 YARD 记录简单的脚本?

ruby - 如何让 Thor 为系统安装的 .thor 文件找到模板?

ruby - 在没有 RVM、Rbenv 的情况下全局更新 ruby​​ OSX

ruby-on-rails - 在 Rails 中向 Integer 类添加方法的最佳位置在哪里?