배열에서 값 찾기
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
'programing tip' 카테고리의 다른 글
Tomcat으로 Spring Boot를 시작할 때 사용자 이름과 비밀번호는 무엇입니까? (0) | 2020.08.03 |
---|---|
iPhone X (시뮬레이터)에서 Cordova 앱이 올바르게 표시되지 않음 (0) | 2020.08.03 |
로드 콜백 후 jQuery UI 대화 상자 제목 변경 (0) | 2020.08.03 |
Vagrant Cache에서 vms 목록 제거 (0) | 2020.08.03 |
Java로 현재 작업 디렉토리를 얻는 방법? (0) | 2020.08.03 |