Ruby 方法等价于“if a in list"在蟒蛇? [英] Ruby methods equivalent of "if a in list" in python?

查看:38
本文介绍了Ruby 方法等价于“if a in list"在蟒蛇?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中我可以用它来检查列表a中的元素:

<预><代码>>>>a = 范围(10)>>>5 个真的>>>16 个错误的

如何在 Ruby 中做到这一点?

解决方案

使用 include?() 方法:

(1..10).include?(5) #=>true(1..10).include?(16) #=>false

(1..10) 是 Ruby 中的 Range, 如果你想要一个 Array(list) :

(1..10).to_a #=>[1,2,3,4,5,6,7,8,9,10]

In python I can use this to check if the element in list a:

>>> a = range(10)
>>> 5 in a
True
>>> 16 in a
False

How this can be done in Ruby?

解决方案

Use the include?() method:

(1..10).include?(5) #=>true
(1..10).include?(16) #=>false

EDIT: (1..10) is Range in Ruby , in the case you want an Array(list) :

(1..10).to_a #=> [1,2,3,4,5,6,7,8,9,10]

这篇关于Ruby 方法等价于“if a in list"在蟒蛇?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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