Reputation: 45
Having an array of arrays like below.
x = [ ["a","b","c","2"], ["d","e","f",""], ["g","h","i","j"] ]
I'm trying to print the Nth element of each array grouped by blocks like below:
Begin
- Value a -
- Value d -
- Value g -
End
Begin
- Value b -
- Value e -
- Value h -
End
Begin
- Value c -
- Value f -
- Value i -
End
Begin
- Value 2 -
- Value -
- Value j -
End
The code below is what I've tried but without success. I'm getting "can't convert String into Integer (TypeError)"
x = [ ["a","b","c","2"], ["d","e","f",""], ["g","h","i","j"] ]
for j in 0.. x.map(&:size).max
p "Begin"
for i in 0..x.size
p x["#{i}"]["#{j}"]
end
p "End"
end
Thanks in advance for any help
#Steve,
If the arrays inside have different size and I try to concatenate a string to the value like below, for the nil values I get error "can't convert nil to string". How can be taken nil as blanck value to avoid that error?
For example, having the array below
x = [ ["a","b"], ["d","e","f"] ]
get the output
Begin
- Value a -
- Value d -
End
Begin
- Value b -
- Value e -
End
Begin
- Value -
- Value f -
End
The code I have so far is, ut I get error for 3rd iteration since first array is smaller than 2nd one:
x = [ ["a","b"], ["d","e","f"] ]
(0...(x.map(&:size).max)).each do |c| puts "Begin" x.each { |array| p "- Value " + array[c] + "-" } puts "End" end
Thanks again for the help
Upvotes: 0
Views: 186
Reputation: 37517
Here's another way:
x.transpose.each do |group|
puts "Begin"
puts group.map {|el| "- Value #{el} -"}
puts "End"
end
Upvotes: 1
Reputation: 36860
You should be doing p x[i][j]
Also you want to use three dots in the range since array elements are numbered from 0 to (array.size - 1). Two dots will give you a range that includes the ending value, three dots gives you a range up to but not including the ending value.
A possibly simpler way...
(0...(x.map(&:size).max)).each do |c|
puts "Begin"
x.each { |array| p array[c] }
puts "End"
end
Upvotes: 1