我在Ruby中使用散列哈希,名为MYMOVIES
,如下所示。
{"127 Hours"=>
{"title"=>"127 Hours",
"year"=>"2010",
"plays"=>1,
"last_played"=>1300489200,
"seen_date"=>"19/3/2011",
"imdb_id"=>"tt1542344",
"rating"=>"6",
"omdbapiurl"=>"http://www.omdbapi.com/?t=127 Hours&y=2010"},
"Zombieland"=>
{"title"=>"Zombieland",
"year"=>"2009",
"plays"=>1,
"last_played"=>1290207600,
"seen_date"=>"20/11/2010",
"imdb_id"=>"tt1156398",
"rating"=>"7",
"omdbapiurl"=>"http://www.omdbapi.com/?t=Zombieland&y=2009"}}
现在,我想获得第一个嵌套哈希的所有键(即title,year,plays,...,omdbapiurl)。
我尝试过:
mynestedhash = MYMOVIES.first
puts mynestedhash.keys.to_s
但我收到错误:
undefined method `keys' for #<Array:0x801c56f8> (NoMethodError)
我该怎么办?
答案 0 :(得分:2)
这应该做:
MYMOVIES.map { |_, h| h.keys }.flatten.uniq
# => ["title", "year", "plays", "last_played", "seen_date", "imdb_id", "rating", "omdbapiurl"]
您的代码无效,因为方法first
返回一个数组,而不是哈希:
MYMOVIES.first
# => ["127 Hours", {"title"=>"127 Hours", ... }]]
更新如果您想获取第一个哈希的密钥,那么您可以这样做:
nested_hash = MYMOVIES.first[1]
nested_hash.keys
# => ["title", "year", "plays", "last_played", "seen_date", "imdb_id", "rating", "omdbapiurl"]
或者:
_, nested_hash = MYMOVIES.first
nested_hash.keys
# => ["title", "year", "plays", "last_played", "seen_date", "imdb_id", "rating", "omdbapiurl"]
答案 1 :(得分:2)
如果所有内部哈希值都具有相同的键,则以下内容就足够了
first_outer_key, first_outer_value = MYMOVIES.first
first_inner_hash = first_outer_value # change name to show what we have
inner_keys = first_inner_hash.keys
如果内部哈希的键可能不同,则应加入它们 就像Priti和toro2k在他们的解决方案中所做的那样。
答案 2 :(得分:1)
require 'pp'
h = {"127 Hours"=>
{"title"=>"127 Hours",
"year"=>"2010",
"plays"=>1,
"last_played"=>1300489200,
"seen_date"=>"19/3/2011",
"imdb_id"=>"tt1542344",
"rating"=>"6",
"omdbapiurl"=>"http://www.omdbapi.com/?t=127 Hours&y=2010"},
"Zombieland"=>
{"title"=>"Zombieland",
"year"=>"2009",
"plays"=>1,
"last_played"=>1290207600,
"seen_date"=>"20/11/2010",
"imdb_id"=>"tt1156398",
"rating"=>"7",
"omdbapiurl"=>"http://www.omdbapi.com/?t=Zombieland&y=2009"}}
pp h.flat_map{|k,v| v.keys}.uniq
<强>输出强>
["title",
"year",
"plays",
"last_played",
"seen_date",
"imdb_id",
"rating",
"omdbapiurl"]
现在看看你的代码在下面不起作用的原因:
h = {"127 Hours"=>
{"title"=>"127 Hours",
"year"=>"2010",
"plays"=>1,
"last_played"=>1300489200,
"seen_date"=>"19/3/2011",
"imdb_id"=>"tt1542344",
"rating"=>"6",
"omdbapiurl"=>"http://www.omdbapi.com/?t=127 Hours&y=2010"},
"Zombieland"=>
{"title"=>"Zombieland",
"year"=>"2009",
"plays"=>1,
"last_played"=>1290207600,
"seen_date"=>"20/11/2010",
"imdb_id"=>"tt1156398",
"rating"=>"7",
"omdbapiurl"=>"http://www.omdbapi.com/?t=Zombieland&y=2009"}}
h.first
#["127 Hours",
# {"title"=>"127 Hours",
# "year"=>"2010",
# "plays"=>1,
# "last_played"=>1300489200,
# "seen_date"=>"19/3/2011",
# "imdb_id"=>"tt1542344",
# "rating"=>"6",
# "omdbapiurl"=>"http://www.omdbapi.com/?t=127 Hours&y=2010"}]
p h.first.grep /keys/
#[]
现在很明显,从#grep
方法来看,Array没有keys
方法。因此,请尝试使用上面的代码使其可行。