我构建了一个数组:
arr = [s1 + s2 + s3 + s4 + s5 + s6]
我想将该数组写入HTML文件。如果我这样做,阵列的所有元素都将被打印出来。
现在,我希望它们之间用新的代码写成,如下所示:
s1 + s2
s3 + s4
s5 + s6
答案 0 :(得分:1)
您可以使用Array#each_slice
:
arr = ["s1" , "s2" , "s3" , "s4" , "s5" , "s6"]
arr.each_slice(2) { |a| p a }
# ["s1", "s2"]
# ["s3", "s4"]
# ["s5", "s6"]
或更准确地说:
file = File.open("abc.html", "w")
arr.each_slice(2) { |a| file.puts a.first + " + " + a.last }
file.close
File.read("abc")
# s1 + s2
# s3 + s4
# s5 + s6
答案 1 :(得分:1)
> arr = ["s1" , "s2" , "s3" , "s4" , "s5" , "s6"]
> arr.each_slice(2){|a| p "#{a[0]} + #{a[1]}"}
#output:
"s1 + s2"
"s3 + s4"
"s5 + s6"
答案 2 :(得分:0)
我假设您的意思是arr = [s1, s2, s3, s4, s5, s6]
尝试
your_file.puts arr[0] + " + " + arr[1]
your_file.puts
your_file.puts arr[2] + " + " + arr[3]
your_file.puts
your_file.puts arr[4] + " + " + arr[5]
空白puts
将在每行之间添加换行符
答案 3 :(得分:0)
arr = %w(s1 s2 s3 s4 s5 s6)
while arr.length != 0
puts arr.shift(2).join("+")
end
输出:
s1+s2
s3+s4
s5+s6