Ruby Arrays

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


Ruby arrays are indexed as integers and starts at 0. Ruby arrays are collection of objects and can be refered by an integer index. Ruby arrays can hold any kind of object like String, Array, Hash etc and are dynamic in nature which means they need to be fixed when initializing.

Ruby Arrays Creation

#!/usr/bin/ruby
# File: arrayexample.rb
 
num1 = Array.new  #initializes array with no fixed size.
num2 = [ "0", "1", "2", "3", "4" ] #creates an array with values 0,1,2,3,4
num3 = Array.new(4) #creates an array with size 4.

Ruby Arrays Example 1

We can use these arrays as follows:

#!/usr/bin/ruby
# File: arrayexample.rb
 
num1 = Array.new  #initializes array with no fixed size.
num1 =  num1 + ["one"]   #num1[] is now "one"
num1 =  num1 + ["two"]   #num1[] is now "one" "two"
num1 =  num1 + ["three"] #num1[] is now "one" "two" "three"
 
puts num1

This would output

one
two
three

Ruby Arrays Example 2

#!/usr/bin/ruby
# File: rubyarrayexample1.rb
 
num1 = Array.new  #initializes array with no fixed size.
num1 =  num1 + [2]   #num1[] is now 2
num1 =  num1 + [1]   #num1[] is now 2 1
num1 =  num1 + [3] #num1[] is now 2 1 3
 
num1 = num1.sort
puts num1

This would output

1
2
3

Sort would work with strings as well as follows:

#!/usr/bin/ruby
# File: rubyarrayexample2.rb
 
num1 = Array.new  #initializes array with no fixed size.
num1 =  num1 + ["sun"]   #num1[] is now sun
num1 =  num1 + ["mon"]   #num1[] is now sun mon
num1 =  num1 + ["tue"] #num1[] is now sun mon tue
 
num1 = num1.sort
puts num1

This would output

mon
sun
tue

Ruby Arrays can have complex objects (which can include number, strings, arrays) in them as follows:

#!/usr/bin/ruby
# File: rubyarrayexample3.rb
 
complex_array = [ [ 1, "two"], [ 3, "four"], [ 5, "six", "seven" ] ]





Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.