开发者

Ruby: how to initialize an array across several lines

开发者 https://www.devze.com 2022-12-14 18:02 出处:网络
I have a small Ruby script where an array is initialized to hold a few strings MyArray = [\"string 1\", \"string 2\" , \"string 2\" ]

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 lik开发者_高级运维e 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?


MyArray = %w(
    string1 
    string2 
    string2
)


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"
]


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

myArray = %w(
   Lorem 
   ipsum 
   dolor
   sit
   amet
)


MyArray = Array.new(
            "string 1"
           ,"string 2" 
           ,"string 2"
          )
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号