2016-02-13 46 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] 

等。

相關問題