Find value in an array

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

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

10条回答
  •  春和景丽
    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
    

提交回复
热议问题