Jump to content

Tutorial: arrays in ruby

- - - - -

  • Please log in to reply
No replies to this topic

#1
mr mike

mr mike

    Learning Programmer

  • Members
  • PipPipPip
  • 96 posts
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.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users