How to Create an Array in Ruby

There are three primary ways to create an array in Ruby: the array literal, building the array and returning an array. An array is most simply defined as a variable that holds a set of values. Each of the three ways to create an array in Ruby is best used in different situations, so being familiar with all of them can be quite useful.

Instructions

  1. Create the Array Literal in Ruby

    • 1

      Choose a variable. In the examples the variable is assigned the term "array". Your variable can be assigned whatever name or symbol you prefer.

    • 2

      Create an array literal from a list of values you already know. Look at the two examples. The first example creates a list of states, the second a list of numbers:
      array = ["Maine", "Michigan", "California"]
      array = [1, 2, 3]

    • 3

      Mix types in a array if you have more than one type of value. Ruby is different than a static languages like Java, in that arrays can hold more than one type. So if your values are both words and numbers the literal array can reflect that. For example:
      array = ["Maine", 7, 12.3]

    • 4

      Utilize the shortcut available for a literal array of just strings. It will save time and effort spent on typing all the quote characters. Instead, you can do this:
      array = %w{Maine Michigan California}

    Build the Array in Ruby

    • 5

      Apply this method when you don't know all the values you want to assign to the array when you write the program.

    • 6

      Use the Array class constructor to make a new empty array object. Here "arr" is now an empty array object, one with no specified values:
      arr = Array.new

    • 7

      Add, or append, elements to the end of the array with the "<<" operator. Used on the end of arrays, "<<" is referred to as the append operator. Here we want to collect a number of strings from the user. Since we don't know what the user will input, we create the empty array and add variables to the end of it:
      arr = Array.new#
      Keep reading lines from the keyboard until "end" is typed:
      while l=gets.chomp and l != "end" do arr << l end

    Return the Array in Ruby

    • 8

      Use the phrase "to_a" for shorthand for "to array". All classes that use the Enumerable module can be turned into arrays with "to_a". This is the most common method to return the array and has the benefit of being easy to change.

    • 9

      Assign, for example, an array with the numbers 1 to 10 to a variable. You could use the long version: a=[1,2,3,4,5,6,7,8,9,10] or use the shorthand: a=(1..10).to_a.
      With the shorthand it would be much easier to change the values from 1 to 10 to, for example, 7 to 22 as shown here:
      a=(7..22).to_a

Tips & Warnings

  • In the array literal any numbers you put your array will be String objects, not Numerics, so don't try to do math with them.

Related Searches:

Comments

You May Also Like

  • How to Create a Multidimensional Array in Ruby

    Though Ruby doesn't provide explicit support for multidimensional arrays, you can implement one yourself if you have a basic knowledge of the...

  • How to Create an Array in C

    Arrays offer the most efficient method for storing lists of data in C. They're very easy for the programmer to create and...

  • How to Learn Ruby

    Ruby is a programming language. Ruby borrows from several other programming languages, such as Java and Perl, and makes the coding easier....

  • How to Create a for Statement in Ruby

    One of the things that makes Ruby preferable to programmers is that it's an object-based language. Programmers can create a for statement...

  • How to Calculate the Value of a Ruby

    Rubies are the fiery red gemstones that traditionally are known as the birthstone of July. The ruby is a variety of corundum....

  • How to Write Math Arrays

    A math array is a way of writing multiplication expressions in terms of columns and rows of pictures or symbols that represent...

  • How to Add Data to an Array

    A data array is typically a set of values that may be related to each other. You can use an array when...

  • What Is a CR Ruby?

    CR rubies are rubies that have the same natural contents and composition as rubies that are mined, but CR rubies are created...

  • How to Create an Array in JavaScript

    Arrays are one of the basic JavaScript datatypes, along with numbers, strings, objects, and functions. JavaScript arrays hold a collection of values,...

  • How to Add Items to an Array in ASP

    The ASP.NET C# language lets you use arrays to store several pieces of data in one variable. After you create the array,...

  • How to Build Ruby Gems

    Ruby is a programming language created by Japanese computer scientist Yukihiro Matsumoto. Ruby libraries are distributed using a centralized network and package...

  • How to Implement Three Stacks in One Array

    Efficient use of system resources is one important skill that separates the masterful programmers from the mediocre. In some circumstances, the ability...

  • How to Input a File in Ruby

    Reading data from and writing data to a file are common tasks in programming. The programming language Ruby has a number of...

  • Martini Drinks With Ruby Red Grapefruit

    Thanks to a plethora of flavored vodkas and the boundless imaginations of bartenders, martini cocktails come in a wide variety of flavors...

  • Three Important Uses of Rubies

    This bracelet contains the closely related gems of rubies and sapphires. necklace with ruby saphire image by Tatyana Parfyonova from Fotolia.com

  • How to Compare Strings in Ruby

    The first thing we do above is assign a value to the string 's' and then a different value to the string...

  • How to Create Synthetic Rubies

    Creating synthetic gemstones requires very high heat. One of the most inexpensive processes for synthesizing rubies is the flame fusion method. First...

  • How to Replace an Arraylist

    An ArrayList class variable stores several values in a list. ArrayLists are similar to one-dimensional arrays, but the class has several additional...

  • How to Use an Array in Mathematics to Find Factors of a Number

    An array shows multiplication tables using objects. This is an easier approach for younger elementary students to visualize, rather than memorize, multiplication...

Related Ads

Featured