I have a small Ruby script where an array is initialized to hold a few strings
我有一个小的Ruby脚本,其中一个数组被初始化以保存一些字符串
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.
但是Ruby标记了这种格式的语法错误我尝试在每行的末尾添加“\”而没有任何成功。
How can this be accomplished in Ruby?
如何在Ruby中完成?
4 个解决方案
#1
32
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"
]
#2
45
MyArray = %w(
string1
string2
string2
)
#3
8
Another way to create an array in multi-line is:
在多行中创建数组的另一种方法是:
myArray = %w(
Lorem
ipsum
dolor
sit
amet
)
#4
1
MyArray = Array.new(
"string 1"
,"string 2"
,"string 2"
)
#1
32
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"
]
#2
45
MyArray = %w(
string1
string2
string2
)
#3
8
Another way to create an array in multi-line is:
在多行中创建数组的另一种方法是:
myArray = %w(
Lorem
ipsum
dolor
sit
amet
)
#4
1
MyArray = Array.new(
"string 1"
,"string 2"
,"string 2"
)