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"
)
Related videos on Youtube
Author by
Eli
Updated on July 09, 2022Comments
-
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 almost 14 years+1 for last hanging comma. It makes for nicer commits when adding an extra item
-
Ghoti over 13 yearsIf 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 almost 12 yearsNote that %w[] is also space-delimited, so if "string1" was changed to "string 1", then MyArray would ==
["string", "1", "string2", "string3"]
-
cevaris almost 9 yearsKeep in mind, this will not work with the OP examples since
%w
delimits on space, andstring 1
will result in ["string", "1"]. You would need to use the[]
constructor. -
dinjas almost 7 yearsWorth noting that you can escape spaces like so:
%w(string\ 1 string\ 2 string\ 3)
-
dinjas almost 7 yearsNot necessarily:
%w(string\ 1 string\ 2 string\ 3)
-
David Gay almost 4 years@dinjas I think at that point I'd rather use the standard array syntax.