简体   繁体   中英

How to print some elements of an array in a new line in Ruby?

I have a Ruby script that outputs an array:

arr = ["filename1", integer1, integer2, "filename2", integer3, integer4, "filename3", integer5, integer6 ...]

What I need is this array to be more readable; I'd like to print only three elements in a single line, so:

"filename1", integer1, integer2,
"filename2", integer3, integer4,
"filename3", integer5, integer6,

I managed to get to the point of having an array of arrays with arr.each_slice(3).to_a :

arr = [["filename1", integer1, integer2], ["filename2", integer3, integer4], ["filename3", integer5, integer6] ...]

but I still can't make each array of the array be printed in a separate line.

Is there a way of doing this?

The ideal output would look something like this:

filename1: integer1, integer2
filename2: integer3, integer4
filename3: integer5, integer6

but I understand that adding the colon after filename is another issue, I would probably have to play around with join() .

The first step is indeed .each_slice(3) as you figured out correctly. I'm assuming arr is already the sliced array.

An easy option would be to just join them together with commas.

arr.each do |elements|
   puts elements.join(', ')
end

If you want the characters used for joining to be different, then you cannot use join, but string interpolation is easy enough.

arr.each do |filename, integer1, integer2|
   puts "#{filename}: #{integer1}, #{integer2}"
end

This will print the string content. If that's what you want, you're done. If you also want to include the quotes around the string, I suggest calling .inspect on it before display.

arr.each do |elements|
   puts elements.map(&:inspect).join(', ')
end
arr.each do |filename, integer1, integer2|
   puts "#{filename.inspect}: #{integer1}, #{integer2}"
end

Formatting an array can be done with the [%] method 1

arr.each_slice(3){|trio| puts "%s: %d, %d" % trio}

Just use the each_slice method of the Enumerator class to split your original array into arrays that consist of five elements each and the join method of the Array class to convert the five element arrays to strings:

 arr.each_slice(3) { |x|
 puts x.join(', ')
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM