harvey
harvey

Reputation: 299

Newlines within an array

I build an array as this :

arr = [s1 + s2 + s3 + s4 + s5 + s6]

I want to write that array into an HTML file. If I do, all elements of the array will be printed in line.

Now, I would like them to be written with new lines in between, like this :

s1 + s2

s3 + s4

s5 + s6

Upvotes: 0

Views: 44

Answers (4)

Gagan Gami
Gagan Gami

Reputation: 10251

> arr = ["s1" , "s2" , "s3" , "s4" , "s5" , "s6"]
> arr.each_slice(2){|a| p "#{a[0]} + #{a[1]}"}
#output:
"s1 + s2"
"s3 + s4"
"s5 + s6"

Upvotes: 1

pangpang
pangpang

Reputation: 8821

arr = %w(s1 s2 s3 s4 s5 s6)
while arr.length != 0
    puts arr.shift(2).join("+")
end

output:

s1+s2
s3+s4
s5+s6

Upvotes: 0

shivam
shivam

Reputation: 16506

You can use Array#each_slice:

arr = ["s1" , "s2" , "s3" , "s4" , "s5" , "s6"]
arr.each_slice(2) { |a| p a }
# ["s1", "s2"]
# ["s3", "s4"]
# ["s5", "s6"]

Or more accurately:

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

Upvotes: 1

kaybee99
kaybee99

Reputation: 4734

I'll assume you mean arr = [s1, s2, s3, s4, s5, s6]

Try

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]

The blank putss will add newlines between each row

Upvotes: 0

Related Questions