Ruby:如何跨多行初始化数组

Eli*_*Eli 23 ruby syntax

我有一个小的Ruby脚本,其中一个数组被初始化以保存一些字符串

MyArray = ["string 1", "string 2" , "string 2" ]
Run Code Online (Sandbox Code Playgroud)

问题是我在初始化列表中有很多字符串,我想打破这一行:

MyArray = [
            "string 1"
           ,"string 2" 
           ,"string 2"
          ]
Run Code Online (Sandbox Code Playgroud)

但Ruby标记了这种格式的语法错误我尝试在每行的末尾添加"\"而没有任何成功.

如何在Ruby中完成?

mis*_*tor 50

MyArray = %w(
    string1 
    string2 
    string2
)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,%w []也是以空格分隔的,因此如果"string1"更改为"string 1",则MyArray将==`["string","1","string2","string3"] (10认同)

now*_*owk 37

你会想要把这个逗号放在这样的项目之后

myarray = [
  "string 1",
  "string 2",
  "string 3"
]
Run Code Online (Sandbox Code Playgroud)

此外,如果您可能正在考虑将逗号放在项目之前,那么在您编写代码时可以轻松评论或类似.你可以留下一个悬挂的逗号,没有真正的不良副作用.

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"
]
Run Code Online (Sandbox Code Playgroud)

  • 最后一个逗号的+1.添加额外项目时,它可以提供更好的提交 (2认同)

Cha*_*tni 9

在多行中创建数组的另一种方法是:

myArray = %w(
   Lorem 
   ipsum 
   dolor
   sit
   amet
)
Run Code Online (Sandbox Code Playgroud)