Kei*_*son 5 ruby arrays if-statement
我正在寻找像Python这样的if-in语句。
从本质上讲,如果x 在 an_array做
这是我正在处理的代码,其中“ line”变量是一个数组。
def distance(destination, location, line)
if destination and location in line
puts "You have #{(n.index(destination) - n.index(location)).abs} stops to go"
end
end
Run Code Online (Sandbox Code Playgroud)
if line.include?(destination) && line.include?(location)
if [destination,location].all?{ |o| line.include?(o) }
if ([destination,location] & line).length == 2
Run Code Online (Sandbox Code Playgroud)
第一个是最清晰的,但最不干燥。
最后一个是最不清晰的,但当您有多个项目需要检查时速度最快。(这是O(m+n)vs O(m*n)。)
我个人会使用中间的,除非速度是最重要的。