如何写"若"在Ruby中声明 [英] How to write an "if in" statement in Ruby

查看:145
本文介绍了如何写"若"在Ruby中声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要找的,如果,在如Python语句对Ruby。

从本质上讲,如果x an_array做
  

这是code我工作,其中变量线是一个数组。

  DEF距离(目的地,地点,路线)
  如果目的地和位置线
    提出你有#{(n.index(目标) - n.index(位置))。ABS}停下来走
  结束
结束


解决方案

 如果line.include(目标)及?&安培; line.include?(位置)如果[目的地位置]。所有{| 2 O | line.include?(O)}如果([目的地位置]放大器;线)。长度== 2

首先是最清晰的,但至少干了。

最后一个是最清楚的,但是当你有多个项目要检查最快的。 (这是 O(M + N) VS O(M * N)

我个人使用中间的一个,除非速度是最重要的。

I'm looking for and if-in statement like Python has for Ruby.

Essentially, if x in an_array do

This is the code I was working on, where the variable "line" is an array.

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

解决方案

if line.include?(destination) && line.include?(location)

if [destination,location].all?{ |o| line.include?(o) }

if ([destination,location] & line).length == 2

The first is the most clear, but least DRY.

The last is the least clear, but fastest when you have multiple items to check. (It is O(m+n) vs O(m*n).)

I'd personally use the middle one, unless speed was of paramount importance.

这篇关于如何写"若"在Ruby中声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆