programing tip

배열에서 값 찾기

itbloger 2020. 8. 3. 08:42
반응형

배열에서 값 찾기


Ruby 1.8.7을 사용하여 Array에서 값을 어떻게 찾을 수 있습니까?


배열 내에 특정 값이 존재하는지 찾으려고 노력하고 있으며 그 경우 Array # include? (value)를 사용할 수 있습니다.

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

다른 의미가 있다면 Ruby Array API를 확인하십시오.


를 사용 Array#select하면 기준에 맞는 여러 요소가 제공됩니다. 그러나 기준에 맞는 배열에서 요소를 가져 오는 방법을 찾고 있다면 Enumerable#detect더 좋은 방법입니다.

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

그렇지 않으면 다음과 같은 어색한 작업을 수행해야합니다.

found = array.select {|e| e == 3}.first

이렇게요?

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

아니면 이렇게?

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

설명서를 참조하십시오 .


이를 위해 Array.select 또는 Array.index사용할 수 있습니다 .


배열에서 하나의 값을 찾으려면 Array#find

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

6.in?

를 제외하고 배열에 값이 있는지 확인하려면 ActiveSupport를 #includes?사용하는 #in?경우 객체를 사용할 때도 사용할 수 있습니다 #include?.

arr = [1, 6]
6.in? arr
#=> true

사용하다:

myarray.index "valuetoFind"

원하는 요소의 인덱스를 반환하거나 배열에 값이 없으면 nil을 반환합니다.


이 답변은 수락 된 답변이 현재 작성된 질문을 다루지 않는다는 것을 알고있는 모든 사람을위한 것입니다.

이 질문은 배열에서 값 찾는 방법을 묻습니다 . 허용되는 답변은 값 배열에 존재 하는지 확인하는 방법을 보여줍니다 .

를 사용하는 예제가 이미 index있으므로 select메소드 를 사용하여 예제를 제공하고 있습니다.

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]

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.


Thanks for replies.

I did like this:

puts 'find' if array.include?(value)

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").

참고URL : https://stackoverflow.com/questions/1734307/find-value-in-array

반응형