Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

Array.new

i no this is probably a rly dumb ?, but, what exactly is Array.new(101) ? and how can I make a new array consisting of the answers to an expression for which the variable is 2..100?
 

khmp

Sponsor

Was this moved from the special support thread?

Array.new(101) creates an array consisting of a 101 elements, all of which are initialized to nil. Now I think you want to utilize a Range object. Which you make reference to at the end of your question. (2..100) That will create a range of numbers starting with the number 2 and ending with 100. A range is created by placing '..' between two objects. Haven't really used them myself for anything but numbers but the documentation leads me to believe you could use them for strings, characters, and possibly more complex objects. You can also use '...' which will create a range between the first element and the last element - 1.

Code:
rang = Range.new(2,5)
rang = 2..5
p rang.to_a # [2, 3, 4, 5]
rang = 2...5
p rang.to_a # [2, 3, 4]

To create an array would be adding an extra level on encapsulation because a Range already has a method to convert it into one. Still though the code to do this would be as follows.
Code:
arr = Array.new((1..101).to_a)
arr = (1..101).to_a

Hope that helps you out The Good King! :thumb:
 
khmp":10j7zkhs said:
Array.new(101) creates an array consisting of only one element holding, you guessed it 101.

Not really. What it does is creating an array of 101 elements, all of which are initialized to nil. To set them to a default value you do something like Array.new(size, value). Just check the Ruby documentation to be sure.
 

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top