From: Stefano Crocco Date: 2011-01-20T19:02:06+09:00 Subject: Re: Array within array question On Thursday 20 January 2011 18:34:26 Josh Rowe wrote: > Hello everyone, this is my first post on this forum and I'm quite new to > ruby. My dilemma is that I've got an array which holds a whole lot of > arrays inside it and I want to print a element of one of the arrays > within the overall array. Got it? Here's an example > > #!/usr/bin/env ruby > card1 = ["Ninja Monster", "monster", 1400] > card2 = ["Ninja Mage", "monster", 1600] > cdname = 0 > deck = [card1,card2] > puts deck[0[cdname]] > > Does anyone(I'm sure most of you) know how to get this to work with a > minimal amount of extra code. > > Regards Joshua puts deck[0][cdname] The [] method of class array (Array#[]), which is what you actually call when writing an_array[3] returns the object with that index in the array. In your case, deck[0] returns the element with index 0, that is the array card1. To retrieve the name of the card, you then access the element with index cdname of this array, again using []. To be more explicit, you can split the above line in two using an intermediate variable: card = deck[0] puts card[cdname] However I think that using arrays to represent cards isn't the best way to go. Arrays usually represent lists of things (for example, it's correct to use them for a deck of cards). The contents of your cards, however, aren't lists, since each item has a different meaning. A better way to represent cards would be to use hashes: card1 = {:name => "Ninja Monster", :type => "monster", :number => 1400} card2 = {:name => "Ninja Mage", :type => "monster", :number => 1600} deck = [card1, card2] puts deck[0][:name] I hope this helps Stefano