Tuesday, 4 February 2014

How To Add Extra Elements Into A Ruby Array

Adding Additional Things Into A Ruby Array

Once you've got your array in Ruby you might want to add extra elements to it. With ruby this is easy.

Create a new array, this time I've created an array of numbers. The keener eyed reader out there will have spotted that you don't need quotations around the numbers - but they do have to be divided by commas. So go ahead and create a new array:

 numbers = [1,2,3,4,5]

Now we simple want to add extra elements onto the end of this array. We accomplish this by a line of code like this:


We then hit enter and here is the output:

[1, 2, 3, 4, 5, "mark"]

There you can see 'Mark' has been added onto the end of the array.


 [1, 2, 3, 4, 5, "mark", "dave"]

And finally we're able to add more and more elements as we want. And that's how to add elements onto an array in Ruby.

No comments:

Post a Comment