Hash相当于大型数组搜索

时间:2014-02-19 17:56:36

标签: ruby arrays hash

我有一个大数组$actor_movie_array,它以这种方式排序:

[actor1, movie1, movie2, movie3...]
[actor2, movie1, movie2, movie3...]
[actor3, movie1, movie2...]

以下方法接受参数actor_name,然后在$actor_movie_array中搜索actor_name

def search by actor(actor_name)  
    result_array = Array.new  
        $actor_movie_array.each {  
        |x| if x[0] == actor_name  
            result_array = x  
            result_array.delete_at(0)  
            break  
        end  
    }  
    return result_array  
end  

如果找到,它将被推送到一个空数组result_array,如下所示:

result_array = [actor1, movie1, movie2, movie3...]

然后,我将删除数组的第一个索引,在本例中为actor1,因为我只希望此actor的剩余电影留在result_array

然而,这实在是效率低下。我知道哈希等价物会更有效,但不知道怎么做。任何人都可以帮助将其转换为哈希等价物吗?

2 个答案:

答案 0 :(得分:0)

我做如下

array_of_array = [ %w[actor1 movie1 movie2 movie3],
                   %w[actor2 movie1 movie2 movie3],
                   %w[actor3 movie1 movie2]
                 ]

def search(ary,actor_name)
  match = ary.find { |a| a.first == actor_name }
  match.nil? ? "no actor found" : match[1..-1] 
end

search(array_of_array,'actor2')
# => ["movie1", "movie2", "movie3"]

search(array_of_array,'actor5')
# => "no actor found"

或者,采取以下方法:

array_of_array = [ %w[actor1 movie1 movie2 movie3],
                   %w[actor2 movie1 movie2 movie3],
                   %w[actor3 movie1 movie2]
                 ]
hsh = Hash[ary.map { |key,*val| [key,val] }]

def search(hash,actor_name)
  hash.fetch(actor_name,"no actor found")
end

search(hsh,'actor2')
# => ["movie1", "movie2"]

search(hsh,'actor5')
# => "no actor found"

答案 1 :(得分:0)

好吧,假设你有一个actors_to_movies = {actor1 => [movie1, movie2, movie3], actor2 => [movie4, movie5, movie6]}形式的哈希,你可以按照你在哈希中查找任何内容的方式循环播放电影列表 - 例如{{1}会给actors_to_movies[actor1]

如果您正在尝试弄清楚如何从您拥有的表单数组生成哈希,那么您可以这样做:

[movie1, movie2, movie3]

(请注意,将大型数组转换为散列映射所需的时间甚至比搜索数组要长 - 但理想情况下,您只需要执行一次。)