Skip to content

Instantly share code, notes, and snippets.

@havenwood
Last active August 29, 2015 14:14
Show Gist options
  • Save havenwood/22bbab49087df6dae8b2 to your computer and use it in GitHub Desktop.
Save havenwood/22bbab49087df6dae8b2 to your computer and use it in GitHub Desktop.
Find path
#https://gist.github.com/apeiros/7c971881bd5c5def09cd
data = {"coord"=>{"lon"=>13.41, "lat"=>52.52}, "sys"=>{"type"=>3, "id"=>162538, "message"=>0.0044, "country"=>"DE", "sunrise"=>1423032146, "sunset"=>1423065487}, "weather"=>[{"a"=>803, "b"=>[{"i"=>803, "j"=>"Clouds", "k"=>"broken clouds", "l"=>"04n"}, {"m"=>803, "n"=>"Clouds", "o"=>"broken clouds", "p"=>"04n"}], "c"=>"broken clouds", "d"=>"04n"}, {"e"=>803, "f"=>"Clouds", "g"=>"broken clouds", "h"=>"04n"}], "base"=>"cmc stations", "main"=>{"temp"=>0.35000000000002, "temp_min"=>-1.1, "temp_max"=>2.8, "pressure"=>1028.5, "humidity"=>91}, "wind"=>{"speed"=>1.66, "deg"=>283.002}, "snow"=>{"3h"=>0.3}, "clouds"=>{"all"=>80}, "dt"=>1423076121, "id"=>2950159, "name"=>"Berlin", "cod"=>200}
def search data, search_key
catch :found do
case data
when Hash
recurring_hash_search data, search_key
when Array
recurring_array_search data, search_key
end
end
end
def recurring_hash_search hash, search_key, stack = []
throw :found, stack if hash.key? search_key
hash.each do |key, value|
case value
when Hash
recurring_hash_search value, search_key, stack + [{key: key}]
when Array
recurring_array_search value, search_key, stack + [{key: key}]
end
end
nil
end
def recurring_array_search array, search_key, stack = []
array.each_with_index do |item, index|
case item
when Hash
recurring_hash_search item, search_key, stack + [{index: index}]
when Array
recurring_array_search item, search_key, stack + [{index: index}]
end
end
nil
end
search data, 'm'
#=> [{:key=>"weather"}, {:index=>0}, {:key=>"b"}, {:index=>1}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment