From: Jim Marshall Date: 2006-11-04T16:00:08+09:00 Subject: Re: Accessing a hash -- Beginner On 2006-11-04, don wrote: > > I have 32 hashes. I would like to key in a hash name and > extract data from it. Like this: > > Enter team: (Enter 'ari', for example) > team_var = gets.chomp > puts team_var['coach'] You could stick (or create from the beginning) those hashes into another hash, say "teams," and then you'll be able to get them by indexing "teams" with user input. > > Above does not work. For one thing, ari is actually $ari. > team_var = '$' + team_var does not work either. > > So simply put, how do you call a hash by name interactively? > > Below is an example of what my code would look like: > > $ari = { > 'name' => 'Arizona Cardinals', > 'team_notes' => 'skank team', > 'qb' => 'Matt Leinart, Kurt Warner', > 'qb_rank' => '', > 'cbs' => '', > 'espn' => '', > 'players' => 'rb Edgerrin James', > 'coach' => 'Denny Green', > 'weekly_notes' => ' wk01 Fitzgerald 133 yds.' > } > teams = {} # Create a new hash to store the individual team hashes teams['ari'] = $ari > print 'team: ' > team = gets.chomp then change the above^ to team = teams[gets.chomp] and you can proceed with > puts team['coach'] > You'll still want some error-checking (what if the user enters 'akaskdfj'?), of course. You can also now access the elements of the individual teams like "teams['ari']['coach']" if you want, although it will often be less cluttered-looking if you pull a reference to the individual team out before you go to work on it, as "team = teams[gets.chomp]" does.