Wednesday, 12 February 2014

How To Add Elements To A Ruby Array Using (.push)

In the last post we examined how to delete elements from the Ruby array using the .pop method. In this short code snippet we're going to take a look at how to use Ruby to add extra elements to the array via the .push method. As always head on over to your shell if you're using Linux and go into irb. Then type out the following code.

new_array = ['Britain','Thailand','USA']

=> ["Britain", "Thailand", "USA"]

And there you have our array of countries like so. Next type in this.


Here we see the .push method along with the latest country we want to add to our Ruby array list.

=> ["Britain", "Thailand", "USA", "Italy"]

Once you hit enter your newly updated array is returned with an addition to it. It's worth mentioning here that we can also push elements into the array via this method <<.

irb(main):003:0> new_array << 'germany'

And the returned output is:

=> ["Britain", "Thailand", "USA", "Italy", "germany"]

Germany being added to our new Ruby array.

No comments:

Post a Comment