Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
TJ Takei
13,362 PointsIsn't "if ...size>0" guard unnecessary for ...each loop? (Ruby Dev Tools)
For containers' "each" method to work, apparently "if (container).size>0" guard seems unnecessary, as long as it is initially set empty. So a code snippet below considered not so educational, is it?
if contact["phone"].size > 0
contact["phone"].each do |item| ... end
end
in "Part 3: Printing The Contact List" video of "Build a Simple Contact List" lecture of Development Tools
1 Answer
Zachary Green
16,359 Pointsyou can use the if statment to maybe tell the user that there is no info to show. I would keep it like that unless you know that contact['phone'] will always have some value in it.
TJ Takei
13,362 PointsTJ Takei
13,362 PointsYes, I agree if and only if we need to do anything with the container itself. However, the "do" block in the lecture has nothing with the container, and it does process something for each item in it. In addition, the "each" loop works even in the case of empty container, that is, it does nothing. Therefore I believe we better refactor the requirement for the container processing and that for the items in it.
Understandably, in the real world situations, many cases require the checking of empty containers. For those the separate "if ...size > 0" would be best practice. Yet, for educational purposes, in the text I would avoid to leave an impression that the "if ...size > 0" guard looks mandatory for the "...each" loop to work. By doing so, it would show the students the power of the "...each" loop to include the empty case.