如何检查数组数组中是否存在键?

时间:2016-05-19 21:45:43

标签: ruby

在没有过多循环的情况下,有没有直接的方法来执行以下操作?

myArray = [["a","b"],["c","d"],["e","f"]]
if myArray.includes?("c")
   ...

我知道如果它只是一个正常的字符数组,这样可以正常工作...但是我想要一个字符数组的数组同样优雅(用于帮助将其转换为元组数组的奖励点)。< / p>

5 个答案:

答案 0 :(得分:5)

如果你只需要一个真/假答案,你可以flatten数组和电话包括:

>> myArray.flatten.include?("c")
=> true

答案 1 :(得分:5)

您可以使用assoc

my_array = [['a', 'b'], ['c', 'd'], ['e', 'f']]

if my_array.assoc('c')
  # ...

它实际上返回整个子阵列:

my_array.assoc('c') #=> ["c", "d"]
如果没有匹配,请

nil

my_array.assoc('g') #=> nil

还有rassoc来搜索第二个元素:

my_array.rassoc('d') #=> ["c", "d"]

答案 2 :(得分:3)

Info:   Security Service(s) started successfully.
Severe:   Class [ com/querydsl/core/dml/UpdateClause ] not found. Error while loading [ class 

Severe:   SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
Severe:   SLF4J: Defaulting to no-operation (NOP) logger implementation
Severe:   SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Severe:   WebModule[/noxml]Servlet dispatcher threw unload() exception
javax.servlet.ServletException: Servlet.destroy() for servlet dispatcher threw exception
at       org.apache.catalina.core.StandardWrapper.unload(StandardWrapper.java:1913)
Severe:   ContainerBase.addChild: start: 
org.apache.catalina.LifecycleException:    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDetailsService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:   Could not autowire field: com.lisawestberg.noxml.dao.FacultyDAO com.lisawestberg.noxml.service.LoginService.dao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.lisawestberg.noxml.dao.FacultyDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5985)

答案 3 :(得分:1)

您可以使用Array#any?

myArray = [["a","b"],["c","d"],["e","f"]]
if myArray.any? { |x| x.includes?("c") }
  # some code here

答案 4 :(得分:1)

find_index方法适用于此:

myArray = [["a","b"],["c","d"],["e","f"]]
puts "found!" if myArray.find_index {|a| a[0] == "c" }

返回值是对的数组索引,如果找不到对,则为nil

您可以通过这种方式捕捉配对的价值(如果没有找到nil):

myArray.find_index {|a| a[0] == "c" } || [nil, nil])[1]
# => "d"