2017-12-01 11 views
0

값이있는 경우에만 self 키 값만 넣으려고합니다. 이 때문에 에스컬레이션 정책이없는 일정 내가 키 self키에 값이 있으면 루비 값을 출력하십시오.

{"schedules"=> 
    [{"id"=>"0000000", 
    "type"=>"schedule", 
    "summary"=>"-PROD-", 
    "self"=>"https://api.pagerduty.com/schedules/", 
    "html_url"=>"https://pagerduty.com/schedules/", 
    "name"=>"-PROD-", 
    "time_zone"=>"America/", 
    "description"=>nil, 
    "privilege"=>nil, 
    "users"=> 
    [{"id"=>"0000000", 
     "type"=>"user_reference", 
     "summary"=>"DOo Kkkk", 
     "self"=>"https://api.pagerduty.com/users/", 
     "html_url"=>"https://target.pagerduty.com/users/"}], 
    "escalation_policies"=>[], 
    "teams"=>[]}, 
} 

이 문제를 정복하기 위해 내 코드의 값을 원하지 않는 예이다 :

somefile = File.open("Schedule_Api.txt", "a+") 
    jdoc.fetch("schedules").each do |schedule| 
    somefile.puts schedule["self"] if schedule["escalation_policies"].exists? == true 
    end 
somefile.close 

이 변수 jdoc은 웹 사이트의 컬입니다. 그리고 이것이 제가 얻은 결과입니다 undefined method가 존재합니까? ' [] : Array (NoMethodError) . Is there another alternative to this then the method가 존재합니까? 어떤 도움이 도움이 될 것입니다! 고맙습니다!

+1

나는 "escalation_policies 키에 값이있는 경우에만"라고 제안합니다. 더 높은 기술 수준이 아니라면 빈 배열은 값이 없다는 것을 나타내지 만, 이것은 다른 사람들에게 혼란 스러울 수 있습니다. "escalation_policies 키의 해시 값이 비어 있지 않은 배열 인 경우에만"(또는 크기> 0) 더 나은 말을하는 것이 좋습니다. –

+0

할거야! 고맙습니다! –

답변

0

보십시오 : 키가 존재하지 않는 경우가 존재하고 않으면 false를 반환

if schedule["escalation_policies"] 

이뿐만 아니라, 해당 값이 : 또한 테스트 할 수

if schedule.has_key?("escalation_policies") 

무.

값의 부재는 항상 하늘의 배열 ([]), 다음 대신 배열 크기> 0

+0

감사합니다! 너도 옳았 어. 나는 아직도 배울 것이 많다. –

1
를 테스트하는 그의 대답에 릭 설리반에 의해 언급 한 바와 같이 schedule["escalation_policies"].empty?, 또는 schedule["escalation_policies"].any?을 사용할 수 있습니다으로 표현 될 경우

.exists?은 Array가 아니라 ActiveRecord의 메서드입니다. 당신이 빈 배열을 테스트 할 경우 모든 값을 테스트하려면

, 당신은 아마

somefile.puts schedule["self"] if schedule["escalation_policies"] 

일을해야하고,

somefile.puts schedule["self"] unless schedule["escalation_policies"].empty? 

을 수행 할

+0

놀라워요! 당신이 옳았! 나는 왜 내가 작성한 코드가 정확하지 않은지 알지만, 최소한 나는 가까이에 있다는 것을 기쁘게 생각한다! 다시 감사합니다! –