ruby 返回随机布尔值的最佳方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8012746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:27:17  来源:igfitidea点击:

Best way of returning a random boolean value

ruby

提问by Chuck Bergeron

I've been using this for some time to return either trueor falsewhen building fake seed data. Just wondering if anybody has a better, more succinct or verbose way of returning either trueor false.

一段时间以来,我一直在使用它来返回truefalse在构建假种子数据时返回。只是想知道是否有人有更好、更简洁或更详细的返回true或 的方式false

rand(2) == 1 ? true : false

回答by tokland

A declarative snippet using Array#sample:

使用Array#sample 的声明性片段:

random_boolean = [true, false].sample

回答by a'r

How about removing the ternary operator.

如何删除三元运算符。

rand(2) == 1

回答by JesseG17

I like to use rand:

我喜欢使用rand

rand < 0.5

rand < 0.5

Edit: This answer used to read rand > 0.5but rand < 0.5is more technically correct. randreturns a result in the half-open range[0,1), so using <leads to equal odds of half-open ranges [0,0.5) and [0.5,1). Using >would lead to UNEQUAL odds of the closed range [0,0.5] and open range (.5,1).

编辑:此答案用于阅读,rand > 0.5rand < 0.5在技​​术上更正确。rand返回半开范围[0,1) 中的结果,因此使用<导致半开范围 [0,0.5) 和 [0.5,1) 的赔率相等。使用>会导致封闭范围 [0,0.5] 和开放范围 (.5,1) 的赔率不相等。

回答by Adam Eberlin

I usually use something like this:

我通常使用这样的东西:

rand(2) > 0

You could also extend Integer to create a to_boolean method:

您还可以扩展 Integer 以创建一个 to_boolean 方法:

class Integer
  def to_boolean
    !self.zero?
  end
end