Find value in an array

后端 未结 10 1802
生来不讨喜
生来不讨喜 2020-12-23 23:52

In Ruby, how can I find a value in an array?

相关标签:
10条回答
  • 2020-12-24 00:45

    Use:

    myarray.index "valuetoFind"

    That will return you the index of the element you want or nil if your array doesn't contain the value.

    0 讨论(0)
  • 2020-12-24 00:46

    If you want find one value from array, use Array#find:

    arr = [1,2,6,4,9] 
    arr.find {|e| e%3 == 0}   #=>  6
    

    See also:

    arr.select {|e| e%3 == 0} #=> [ 6, 9 ]
    e.include? 6              #=> true
    

    To find if a value exists in an Array you can also use #in? when using ActiveSupport. #in? works for any object that responds to #include?:

    arr = [1, 6]
    6.in? arr                 #=> true
    
    0 讨论(0)
  • 2020-12-24 00:46

    This answer is for everyone that realizes the accepted answer does not address the question as it currently written.

    The question asks how to find a value in an array. The accepted answer shows how to check whether a value exists in an array.

    There is already an example using index, so I am providing an example using the select method.

    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]
    
    0 讨论(0)
  • 2020-12-24 00:46

    You can go for array methods.

    To see all array methods use methods function with array. For Example,

    a = ["name", "surname"] 
    a.methods
    

    By the way you can use different method for checking value in array You can use a.include?("name").

    0 讨论(0)
提交回复
热议问题