Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: how to initialize an array across several lines

Tags:

syntax

ruby

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?

like image 748
Eli Avatar asked Dec 27 '09 07:12

Eli


People also ask

How do you create a nested array in Ruby?

To add data to a nested array, we can use the same << , or shovel, method we use to add data to a one-dimensional array. To add an element to an array that is nested inside of another array, we first use the same bracket notation as above to dig down to the nested array, and then we can use the << on it.

How do you create a multiline string in Ruby?

Multiline Syntax in Ruby You can use the the syntax `<<-TEXT` to start a multiline string in Ruby.


4 Answers

MyArray = %w(
    string1 
    string2 
    string2
)
like image 56
missingfaktor Avatar answered Oct 23 '22 02:10

missingfaktor


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"
]
like image 30
nowk Avatar answered Oct 23 '22 01:10

nowk


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

myArray = %w(
   Lorem 
   ipsum 
   dolor
   sit
   amet
)
like image 43
Chandra Patni Avatar answered Oct 23 '22 02:10

Chandra Patni


MyArray = Array.new(
            "string 1"
           ,"string 2" 
           ,"string 2"
          )
like image 1
khelll Avatar answered Oct 23 '22 03:10

khelll