Reputation: 321
I'm new to coding in Ruby, and I have a quick question about iterating over multi-dimensional arrays. I need to know what is appropriate in terms of formatting. This is my code for iterating over the array 'colors'
colors = [['red','orange'],['purple','blue'],['yellow','green']]
colors.each{ |sub_arrays|
sub_arrays.each{ |items|
puts "#{items}"
}
}
This is the answer code
colors = [['red', 'orange'],['purple','blue'],['yellow','green']]
colors.each do |sub_arrays|
sub_arrays.each do |items|
puts "#{items}"
end
end
I'm asking if this was just a mistake on the answer sheet or if this is actually how you're supposed to format this code. Also, is it better to use keywords 'do' and 'end' as supposed to curly brackets? And should I put the element |sub_arrays| or |items| on the same line as the .each method? Thanks!
Upvotes: 1
Views: 284
Reputation: 2496
Formatting in Ruby is pretty much only convention, not really enforced as it is some other languages like Python, but still very important for the sake of readability and avoiding certain pitfalls due to the "freedom" of the syntax.
As for convention, the example is "wrong" in the regard of indentation, the second do..end
loop should be indented from the outer loop.
As for {..}
vs do..end
, it is largely subjective, but one roll of thumb to use is this: if the statement is going to extend beyond one line or if it is nested, then prefer the do..end
syntax. Nested use of {..}
just looks ugly, and should be avoided. This follows the Ruby way of "ugly code should look ugly".
There is some additional syntatic sugar that could be applied to avoid the use of any type of block, but that is kinda extending beyond the scope of the question.
If I personally were to write that statement, I would prefer something like this:
colors.each do |sub_arrays|
sub_arrays.each { |items| puts items }
end
or...
colors.each do |sub_arrays|
sub_arrays.each do |item|
puts items
end
end
But I would definitely avoid the use of nested curly braces. I don't believe anyone would agree the keeping the same indent on the inner loop is the "proper" way to do that. Consecutive end
on the same indent level just looks bad and reeks of bad formatting.
Upvotes: 1