Find value in an array

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

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

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

    Like this?

    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]               #=> []
    

    or like this?

    a = [ "a", "b", "c" ]
    a.index("b")   #=> 1
    a.index("z")   #=> nil
    

    See the manual.

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

    I know this question has already been answered, but I came here looking for a way to filter elements in an Array based on some criteria. So here is my solution example: using select, I find all constants in Class that start with "RUBY_"

    Class.constants.select {|c| c.to_s =~ /^RUBY_/ }
    

    UPDATE: In the meantime I have discovered that Array#grep works much better. For the above example,

    Class.constants.grep /^RUBY_/
    

    did the trick.

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

    Using Array#select will give you an array of elements that meet the criteria. But if you're looking for a way of getting the element out of the array that meets your criteria, Enumerable#detect would be a better way to go:

    array = [1,2,3]
    found = array.select {|e| e == 3} #=> [3]
    found = array.detect {|e| e == 3} #=> 3
    

    Otherwise you'd have to do something awkward like:

    found = array.select {|e| e == 3}.first
    
    0 讨论(0)
  • 2020-12-24 00:31

    you can use Array.select or Array.index to do that.

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

    I'm guessing that you're trying to find if a certain value exists inside the array, and if that's the case, you can use Array#include?(value):

    a = [1,2,3,4,5]
    a.include?(3)   # => true
    a.include?(9)   # => false
    

    If you mean something else, check the Ruby Array API

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

    Thanks for replies.

    I did like this:

    puts 'find' if array.include?(value)
    
    0 讨论(0)
提交回复
热议问题