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
Andrew Carr
10,979 PointsHow does Ruby recognize elements in '.each' function?
This is a general question. Let's say I have following code:
line_count = 0
File.open("text.txt").each {|line| line_count += 1}
puts line_count
Now I've used the code an miraculously it does count the lines. That being said, I don't get how it knows to count them. I can replace 'dogs' for 'line' and it will still count the lines. Furthermore, opening a random text file, how does Ruby choose to break it into lines in general and not, per se, words? For a '.each' function that seems more reasonable to me. Again, very n00bish here, so thank you for your patience.
Thanks!
Andrew Carr
2 Answers
Geoff Parsons
11,679 PointsFile.open returns an IO object. If we look at the IO documentation for the each method you can see that it:
Executes the block for every line in ios, where lines are separated by sep. ios must be opened for reading or an IOError will be raised.
In your case the line variable in your block is just where you are choosing to store the line when it is yielded to the block. That's why changing the name to 'dogs' didn't matter. If you'd like to be more specific in your code you could also use #each_line. Each class, including those you create, can define how they handle enumerating with #each should they choose to implement it at all.
Also as a shortcut you could use the following:
line_count = File.open('text.txt').each_line.count
Andrew Carr
10,979 PointsThanks!