CSC/ECE 517 Summer 2008/wiki1 6 arraysandhashes: Difference between revisions
Jump to navigation
Jump to search
(→Arrays) |
|||
Line 11: | Line 11: | ||
==== Creating an Array ==== | ==== Creating an Array ==== | ||
One way to create an array is to use the new class method: | One way to create an array in Ruby is to to use the new class method: | ||
months = Array.new(12) | months = Array.new(12) | ||
This creates an empty array named months. | This creates an empty array named months. This is similar to the Java initialization: | ||
String[] months = new String[12] | |||
An array can also be created by allowing the initialization of a default value to each element in the array: | |||
months = Array.new(12, "month") | |||
==== Identifying Arrays ==== | ==== Identifying Arrays ==== | ||
==== Adding Elements ==== | ==== Adding Elements ==== | ||
==== Removing Elements ==== | ==== Removing Elements ==== |
Revision as of 22:10, 2 June 2008
Arrays and Hashes
Arrays and hashes are built into Ruby. Arrays, of course, are built into Java too, but hashes are only available through library classes. Compare Ruby and Java arrays, as well as hashes. Write equivalent code sequences in the two languages that illustrate the convenience of programming these constructs in both languages.
Arrays
While Java and Ruby both provide built-in support for arrays, they differ in the operations that can be performed on them.
Comparison of Common Operations in Ruby and Java
Creating an Array
One way to create an array in Ruby is to to use the new class method:
months = Array.new(12)
This creates an empty array named months. This is similar to the Java initialization:
String[] months = new String[12]
An array can also be created by allowing the initialization of a default value to each element in the array:
months = Array.new(12, "month")