Ruby: how to initialize an array across several lines

22,712

Solution 1

You will want to put the comma, after the item like so

myarray = [
  "string 1",
  "string 2",
  "string 3"
]

Also, if you might be thinking of putting the comma before the item, for say easy commenting or something like that while your working out your code. You can leave a hanging comma in there with no real adverse side effects.

myarray_comma_ended = [
  "test",
  "test1",
  "test2", # other langs you might have to comment out this comma as well
  #"comment this one"
]

myarray_no_comma_end = [
  "test",
  "test1",
  "test2"
]

Solution 2

MyArray = %w(
    string1 
    string2 
    string2
)

Solution 3

Another way to create an array in multi-line is:

myArray = %w(
   Lorem 
   ipsum 
   dolor
   sit
   amet
)

Solution 4

MyArray = Array.new(
            "string 1"
           ,"string 2" 
           ,"string 2"
          )
Share:
22,712

Related videos on Youtube

Eli
Author by

Eli

Updated on July 09, 2022

Comments

  • Eli
    Eli almost 2 years

    I have a small Ruby script where an array is initialized to hold a few strings

    MyArray = ["string 1", "string 2" , "string 2" ]
    

    The problem is that I have quite a few strings in the initialization list and I would like to break the line:

    MyArray = [
                "string 1"
               ,"string 2" 
               ,"string 2"
              ]
    

    but Ruby flags a syntax error for this format I tried adding "\" to the end of each line without any success.

    How can this be accomplished in Ruby?

  • Marc-André Lafortune
    Marc-André Lafortune almost 14 years
    +1 for last hanging comma. It makes for nicer commits when adding an extra item
  • Ghoti
    Ghoti over 13 years
    If you paste this into IRB (or an editor and run it) it bombs, traditionally before ruby 1.9 you had to keep the delimiters (, or .) at the end of the line to keep the parser happy. 1.9 allows you to move the . for chaining methods to the line below, but not commas.
  • danneu
    danneu almost 12 years
    Note that %w[] is also space-delimited, so if "string1" was changed to "string 1", then MyArray would == ["string", "1", "string2", "string3"]
  • cevaris
    cevaris almost 9 years
    Keep in mind, this will not work with the OP examples since %w delimits on space, and string 1 will result in ["string", "1"]. You would need to use the [] constructor.
  • dinjas
    dinjas almost 7 years
    Worth noting that you can escape spaces like so: %w(string\ 1 string\ 2 string\ 3)
  • dinjas
    dinjas almost 7 years
    Not necessarily: %w(string\ 1 string\ 2 string\ 3)
  • David Gay
    David Gay almost 4 years
    @dinjas I think at that point I'd rather use the standard array syntax.