在轨道中生成随机固定小数



我正在尝试在我的rails应用程序中生成随机数据。但是我对十进制金额有问题。我收到错误说范围的价值不好。

while $start < $max
        $donation = Donation.new(member: Member.all.sample, amount:  [BigDecimal('5.00')...BigDecimal('200.00')].sample,
                                 date_give: Random.date_between(:today...Date.civil(2010,9,11)).to_date,
                                 donation_reason: ['tithes','offering','undisclosed','building-fund'].sample )
        $donation.save
        $start +=1
      end

如果你想要两个数字之间的随机小数,样本不是办法。相反,请执行如下操作:

random_value = (200.0 - 5.0) * rand() + 5

另外两个建议:
1.如果您已经实现了此功能,那就太好了,但它看起来不是标准的Random.date_between(:today...Date.civil(2010,9,11)).to_date
2. $variable 表示 Ruby 中的全局变量,所以你可能不希望这样。

更新---真正获得随机日期的方法

require 'date'
def random_date_between(first, second)
  number_of_days = (first - second).abs
  [first, second].min + rand(number_of_days)
end
random_date_between(Date.today, Date.civil(2010,9,11))
=> #<Date: 2012-05-15 ((2456063j,0s,0n),+0s,2299161j)>
random_date_between(Date.today, Date.civil(2010,9,11))
=> #<Date: 2011-04-13 ((2455665j,0s,0n),+0s,2299161j)>

最新更新