Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Ruby Objects and Classes Ruby Objects and Classes Instantiation

Ruby Help

Why won't this work?

ruby.rb
string = String.new("string")
array = Array.new["array"]

3 Answers

Josip Dorvak
Josip Dorvak
18,126 Points

The way you are calling Array.new is wrong. A function is called using (), however ruby allows you to omit them, BUT you must have a space in between the function name and parameters.

You can fix it in a number of ways, the easiest is just add a space between new and your array: (array=Array.new ["array"]). Or you can do a shorthand version and write array = ["array"].

Reading the ruby docs is a very good place to read how to create objects and how to use methods

Docs for Array(http://ruby-doc.org/core-2.2.0/Array.html#method-c-new)

Dylan Shine
Dylan Shine
17,565 Points

Because that's not a legal way of instantiating an array in Ruby.

You can either:

arr = Array.new
arr.push("One") or arr[0] = "One"

or simply do it in one line:

arr = ["One"]
Tim Knight
Tim Knight
28,862 Points

Sara, you're on the write track with using brackets, but using them basically removes the need to specify Array.new, they function as shorthand. So you can do:

array = ['array', 'another', 'yet another']

Another trick is to turn a list of words into an array using %w.

array2 = %w{array another another}