加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – rand(Range) – 没有将Range隐式转换为Integer

发布时间:2020-12-17 03:33:15 所属栏目:百科 来源:网络整理
导读:关于问题 How to create a random time between a range 的后续行动. 内核#rand适用于时间范围: require 'time'rand(Time.parse('9 am')..Time.parse('11:30 am')) 但是当我尝试使用自定义类时,我最终得到了错误: `rand’: no implicit conversion of Rang
关于问题 How to create a random time between a range
的后续行动.

内核#rand适用于时间范围:

require 'time'
rand(Time.parse('9 am')..Time.parse('11:30 am'))

但是当我尝试使用自定义类时,我最终得到了错误:

`rand’: no implicit conversion of Range into Integer (TypeError)

class Int
  include Comparable

  attr_reader :num

  def initialize(num)
    @num = num
  end

  def succ
    Int.new(num + 1)
  end

  def <=>(other)
    num <=> other.num
  end

  def to_s
    "Int(#{num})"
  end

  def to_int
    @num
  end

  alias_method :inspect,:to_s
end

puts rand(Int.new(1)..Int.new(3))

为什么?我在自定义课程中缺少什么?我们可以在rand(Range)中使用这样的自定义类吗?

解决方法

我不知道任何关于Kernel#rand对Range参数的期望的文档,但我们可以通过覆盖respond_to来了解正在发生的事情?在你的班上然后看着事情崩溃:

def respond_to?(m)
  puts "They want us to support #{m}"
  super
end

这样做告诉我们rand想要调用Int实例上的#和#方法.鉴于rand(a..b)设计用于处理整数,这确实有一定意义.

所以我们抛出了加法和减法的快速实现:

def -(other)
  self.class.new(to_int - other.to_int)
end

def +(other)
  self.class.new(to_int + other.to_int)
end

我们开始通过调用rand来获得rand Ints.

我不确定在哪里(或者如果)记录下来,所以你不得不原谅一点挥手.我通常花一些时间围绕Ruby源代码来回答这类问题,但我现在没时间.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读