Ruby 方法相当于 Python 中的“if a in list”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1529986/
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
Ruby methods equivalent of "if a in list" in python?
提问by noomz
In python I can use this to check if the element in list a
:
在 python 中,我可以使用它来检查列表中的元素a
:
>>> a = range(10)
>>> 5 in a
True
>>> 16 in a
False
How this can be done in Ruby?
这如何在 Ruby 中完成?
回答by pierrotlefou
Use the include?()
method:
使用include?()
方法:
(1..10).include?(5) #=>true
(1..10).include?(16) #=>false
EDIT:
(1..10)
is Rangein Ruby , in the case you want an Array(list) :
编辑:
(1..10)
是Ruby 中的Range,如果您想要一个 Array(list) :
(1..10).to_a #=> [1,2,3,4,5,6,7,8,9,10]
回答by johannes
Range has the === method, which checks whether the argument is part of the range.
Range 有 === 方法,它检查参数是否是范围的一部分。
You use it like this:
你像这样使用它:
(1..10) === 5 #=> true
(1..10) === 15 #=> false
or as you wrote it:
或如您所写:
a= (1..10)
a === 5 #=> true
a === 16 #=> false
You must be sure the values of the range and the value you are testing are of compatible type, otherwise an Exception will be thrown.
您必须确保范围的值和您正在测试的值是兼容的类型,否则将抛出异常。
(2.718..3.141) === 3 #=> true
(23..42) === "foo" # raises exception
- This is done in O(1), as Range#===(value) only compares value with Range#first and Range#last.
- If you first call Range#to_a and then Array#include?, it runs in O(n), as Range#to_a, needs to fill an array with n elements, and Array#include? needs to search through the n elements again.
- 这是在 O(1) 中完成的,因为 Range#===(value) 仅将值与 Range#first 和 Range#last 进行比较。
- 如果先调用 Range#to_a,然后调用 Array#include?,它的运行时间为 O(n),因为 Range#to_a 需要用 n 个元素填充数组,而 Array#include? 需要再次搜索 n 个元素。
If you want to see the difference, open irb and type:
如果您想查看差异,请打开 irb 并键入:
(1..10**9) === 5 #=> true
(1..10**9).to_a.include?(5) # wait some time until your computer is out of ram and freezess