Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJennifer Krohn
1,661 PointsSpecify number of items in an array?
The Teacher's Notes section states: Create an array with 3 items: array = Array.new(3, "Jason")
How does it know to expect three items? Isn't the the 3 just a number being passed?
3 Answers
Jorge Felico
15,543 PointsThere are numerous ways for you to create an array;
thearrray = [4, "hi", true] #this creates an array with "4, 'hi', true" as the initial values
or
thearray = Array.new(3) #this creates an array with 3 nil values.
Donald McLamb
2,867 PointsHi Jennifer,
array = Array.new(3, "Jason")
when a new class is created,
.new
The new object
array
will attempt to pass the arguments that you have
(3, "Jason")
into a method called
def initialize(a,b,c)
if you pass in more or less then three arguments, I imagine you are getting an error.
Basically the .new method recreates everything that is inside of the class. When recreating a class it will look to the initialize method to see what needs to be passed. The 3 is the amount of arguments,
def initialize(a,b,c)
Not the actual integer, 3.
Jennifer Krohn
1,661 PointsThanks
Matthew Day
6,740 PointsMatthew Day
6,740 PointsJennifer, in addition to the what Jorge has already mentioned, the reason that 3 is not a number being passed is because the new array is defined by the parameters within the parentheses. I think the reason this initially does not make sense, though, is because the entire video shows how to create the content of arrays using brackets. So one way to look at this is to use parentheses when you want the contents of the array to be calculated (in this case, fill it with "Jason" three times) and to use brackets when you want to list out the contents yourself (for example, "eggs" "milk" "bread"). Great question!