json 문서에서 영화 및 프로그램과 관련된 정보를 검색해야합니다.중첩 된 선택 블록 피하기
unique_nos = js['navigation']['category'].select{|n| n['name']=="Home"}.first['category'].select{|s| s['name']=="#{type}"}.first['category'].select{|k| k['name']=='Movie Studios'}.first['category'].map{|l| l['categoryId']}
TV 프로그램에도 동일하게 적용됩니다.
unique_nos = js['navigation']['category'].select{|n| n['name']=="Home"}.first['category'].select{|s| s['name']=='TV'}.first['category'].select{|k| k['name']=='Networks'}.first['category'].map{|l| l['categoryId']}
같은 작업을 수행하는 코드 중복을 피하고 싶습니다. 이 블록을 매개 변수로 전달하여 동적 일 수 있습니다. 메타 프로그래밍으로 이것을 달성 할 수있는 방법이 있습니까?
def find_unique_nos(js, type, category)
js['navigation']['category'].find{|n| n['name'] == "Home" }['category']
.find{|s| s['name'] == type }['category']
.find{|k| k['name'] == category }['category']
.map{|l| l['categoryId']}
end
당신이 원하는 경우
json fragement를 게시 할 수 있습니까? –
첫 번째 예제에서'unique_nos (js, "TV", "Networks") 메소드를 호출 할 때'unique_nos (js, "# {type}", "Movie Studios")'두 번째? (우리가 @ Uri의 대답에서 우리가 같은 줄을 따라 생각하고 있으며, 나는'js '라는 인수를 잊어 버렸음을 알 수 있습니다.) –
당신이 가지고있는 것은 쇠사슬을 묶는 것이지 둥지를 만드는 것이 아닙니다. – sawa