Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Tutorial: arrays in ruby

linked list array

  • Please log in to reply
No replies to this topic

#1 mr mike

mr mike

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 89 posts

Posted 23 December 2010 - 12:44 PM

Hello again, welcome back to my tutorials on ruby. Today I will show showing a few ways arrays work in ruby through code examples.

# we'll make an array of fruit
fruit = ['oranges', 'apples', 'pears', 'tomatoes']

Now lets display the array:
puts fruit

Now lets play with the array:
#display first element in array
fruit[0]
#display third element in array
fruit[2]
#undefined element will display nil
fruit[8](this is an example of freedom ruby allows compared to other languages like java or c++)
#display array first from the right
fruit[-1]
#display array second from the right
fruit[-2]
#display first three elements of array
fruit[0..2]
#... add some more ...

Here is an array of an array, ie a multidimensional array:
groups = [[fruit], ['onion', 'potato', 'mushroom', 'celery'], ['milk', 'cheese', 'yogurt', 'otherdairy']]
#	the first array
a[0][0]
#likewise this will show the 3rd element of the second
#	element array
a[1][2]
#...you play around some more ... 

This is the end of my example by show tutorial of arrays. Hope you enjoyed. My next post will be after the holidays.
Merry Christmas:c-smile::c-smile::c-smile:

Oh one more thing about arrays, but not the last:
Arrays can also be used as a linked list, a stack, or a set.

Edited by Roger, 06 January 2011 - 12:01 PM.

  • 0





Also tagged with one or more of these keywords: linked list, array

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download