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 trialNicholas Lee
12,474 Pointswhy |account| for a find method?
To make a find method I do not quite understand this line of code. Specifically, how |account| plays a role. '''def self.find_for(first_name, last_name) @accounts.find{|account| account.full_name == "#{first_name} #{last_name}"}'''
1 Answer
Maciej Czuchnowski
36,441 PointsThere are many accounts and they are all stored together in the @accounts instance variable. This method goes through them, checks each account (ONE AT A TIME!) to see if that accoun't full_name parameter is equal to the first_name + last_name of the person we are looking for. This |account| construct is very important and you will see it a lot in Ruby (and later, in Rails etc.). When the method is going through each account individually, it needs to stores them temporarily somewhere, in the "account" local variable in this case. So it does something like this:
Take the first account from the whole @accounts set, put this single account temporarily in the "account" variable, see if that account matches the query. If it doesn't match, take the second account from the @accounts and put it temporarily in the "account" variable again (overwriting the previous one, since it wasn't the one we were looking for), see if this one matches. If not, take the third, put it in the "account" variable etc...
It doesn't need to be named "account", this could as well be:
@accounts.find{|x| x.full_name == "#{first_name} #{last_name}"
"Go through each account and use the x variable to store each of them temporarily while doing comparisons"
You just need to match the thing between the || symbols and the thing before the .full_name. And it would do the same thing. It's a convention to use the singular form of the noun, to make it more readable and intuitive.
Hope this description helps.
Nicholas Lee
12,474 PointsNicholas Lee
12,474 PointsWow. Much more clear. Thank you very much.