在 Ruby 中,如何在数组中找到值?
你可以使用 数组,选择或者 数组索引来做到这一点。
用途:
myarray.index "valuetoFind"
如果数组不包含该值,则返回所需元素的索引或 nil。
像这样吗?
a = [ "a", "b", "c", "d", "e" ] a[2] + a[0] + a[1] #=> "cab" a[6] #=> nil a[1, 2] #=> [ "b", "c" ] a[1..3] #=> [ "b", "c", "d" ] a[4..7] #=> [ "e" ] a[6..10] #=> nil a[-3, 3] #=> [ "c", "d", "e" ] # special cases a[5] #=> nil a[5, 1] #=> [] a[5..10] #=> []
还是这样?
a = [ "a", "b", "c" ] a.index("b") #=> 1 a.index("z") #=> nil
请参阅说明书。
如果要确定数组中是否存在某个值,可以使用 数组 # include? (值):
a = [1,2,3,4,5] a.include?(3) # => true a.include?(9) # => false
如果你指的是别的,检查 Ruby 数组 API
谢谢你的回复。
我喜欢这样:
puts 'find' if array.include?(value)
我知道这个问题已经得到了回答,但是我来这里寻找一种基于某些条件筛选 Array 中元素的方法。下面是我的解决方案示例: 使用 select,我找到 Class 中以“ RUBY _”开头的所有常量
select
Class.constants.select {|c| c.to_s =~ /^RUBY_/ }
同时,我发现 Array # grep 工作得更好,
Class.constants.grep /^RUBY_/
成功了。
这个答案适用于每一个认识到已接受的答案并没有按照当前的写法解决问题的人。
该问题询问如何在数组中使用 找到值。接受的答案显示如何检查数组中的值 存在。
已经有一个使用 index的示例,所以我提供了一个使用 select方法的示例。
index
1.9.3-p327 :012 > x = [1,2,3,4,5] => [1, 2, 3, 4, 5] 1.9.3-p327 :013 > x.select {|y| y == 1} => [1]
使用 Array#select将为您提供满足条件的元素数组。但是,如果您正在寻找一种方法,将符合条件的元素从数组中取出,那么 Enumerable#detect将是一种更好的方法:
Array#select
Enumerable#detect
array = [1,2,3] found = array.select {|e| e == 3} #=> [3] found = array.detect {|e| e == 3} #=> 3
否则你就得做一些尴尬的事情,比如:
found = array.select {|e| e == 3}.first
如果希望从 Array 中查找 一值,请使用 Array#find:
Array#find
arr = [1,2,6,4,9] arr.find {|e| e % 3 == 0} #=> 6
如果要从 Array 中查找 多个值,请使用 Array#select:
arr.select {|e| e % 3 == 0} #=> [ 6, 9 ] e.include? 6 #=> true
若要查找 Array 中是否存在值,还可以在使用 ActiveSupport 时使用 #in?。#in?适用于任何响应 #include?的对象:
#in?
#include?
arr = [1, 6] 6.in? arr #=> true
可以使用数组方法。
要查看所有数组方法,请使用带有数组的 methods函数。 例如,
methods
a = ["name", "surname"] a.methods
顺便说一下,你可以使用不同的方法来检查数组中的值 你可以使用 a.include?("name")。
a.include?("name")
let arr = [ { name:"string 1", value:"this", other: "that" }, { name:"string 2", value:"this", other: "that" } ]; let h = arr.find(x => x.name == 'string 1') ?? arr[0] console.log(h);