2016-02-13 59 views
0

我从我的模型中获取了一些数据(在一个名为results的变量中),我想根据它们的键将它组织到数组中。 I.E,每个genreName值应该被推入到genres []数组中,每个actorID到cast []数组中。如何根据数字键将数据值排列到数组中 - Ruby

results

#<Genre genreName: "Fantasy"> 
#<Genre genreName: "Comedy"> 
#<Genre genreName: "Children"> 
#<Genre genreName: "Animation"> 
#<Genre genreName: "Adventure"> 
#<Actor actorID: "tom_hanks", actorName: "Tom Hanks"> 
#<Actor actorID: "tim_allen", actorName: "Tim Allen"> 
#<Actor actorID: "don_rickles", actorName: "Don Rickles"> 
#<Actor actorID: "jim_varney", actorName: "Jim Varney"> 
#<Actor actorID: "wallace_shawn", actorName: "Wallace Shawn"> 
#<Director directorID: "john_lasseter", directorName: "John Lasseter"> 
#<Country countryName: "USA"> 
#<Location locationName: "N/A"> 

什么你有什么建议?我正在尝试在Ruby中完成此操作。

编辑

也许会更有意义,所有的对象值添加到哈希,但我担心唯一的密钥名称...

+0

您应该将'results'显示为一个有效的Ruby对象。假设它是一个字符串数组:'results = [“#,...”#“]'。 –

+1

...如果'results'是一组类实例,需要说。 –

回答

0
genre_names = results.map { |object| object.genreName if object.class.name == "Genre" } 

这将通过每个迭代对象,并通过仅包含类“流派”类的对象返回一个包含每个genreName字段的数组。然后你可以做一些类似的其他领域。

0

(编辑:我可能误解了这个问题我把数据是一个字符串数组,但似乎更有可能的是,他们是类的实例)

results = <<_.lines 
#<Genre genreName: "Fantasy"> 
#<Genre genreName: "Comedy"> 
#<Genre genreName: "Children"> 
#<Genre genreName: "Animation"> 
#<Genre genreName: "Adventure"> 
#<Actor actorID: "tom_hanks", actorName: "Tom Hanks"> 
#<Actor actorID: "tim_allen", actorName: "Tim Allen"> 
#<Actor actorID: "don_rickles", actorName: "Don Rickles"> 
#<Actor actorID: "jim_varney", actorName: "Jim Varney"> 
#<Actor actorID: "wallace_shawn", actorName: "Wallace Shawn"> 
#<Director directorID: "john_lasseter", directorName: "John Lasseter"> 
#<Country countryName: "USA"> 
#<Location locationName: "N/A"> 
_ 

你可以这样做:

R =/
    \b  # Match a word break 
    (genreName|actorID|cast) # Match one of three strings in capture group 1 
    \b  # Match a word break 
    (?=  # Begin a positive lookahead 
     :\s+\" # Match : >= 1 whitespace double quote 
     (\w+) # Match >= 1 word characters in capture group 2 
     \"  # Match double quote 
    )   # End postive lookahead 
    /x  # Extended/free-spacing regex definition mode 


h = results.each_with_object({ genreName: [], actorID: [], cast: [] }) { |s,h| 
    s.scan(R) { h[$1.to_sym] << $2 } } 
    #=> {:genreName=>["Fantasy", "Comedy", "Children", "Animation", "Adventure"], 
    # :actorID=>["tom_hanks", "tim_allen", "don_rickles", "jim_varney", "wallace_shawn"], 
    # :cast=>[]} 

然后

actorID = h[:actorID] 

等。

相关问题