Find value in an array

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

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

10条回答
  •  Happy的楠姐
    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
    

提交回复
热议问题