Can you explain to me what it's doing here i.name[name]?
Sure. Basically, I just used the "index" method on String the same way that you'd use it on an Array -- the side effect of this is that it essentially searches the string for the given contents and returns the substring if those contents are found (or nil if the given contents don't exist). The most interesting thing about this, to me, is that it works just as well with substrings as it does with regular expressions.
The i.name portion simply returns the name of an individual item. Considering this was used in a block passed to select, we're essentially scanning each item in the database and filtering them based on the name given by searching each one's name for the given substring.
I'm interested in that rescue clause. Is that so that you can conveniently just reference the id on your selected array, and if it can't find the id property/method it rescues and returns nil?
Pretty much. It's also in case an exception occurs at any step along the way -- but it will only rescue exceptions which are descendants of StandardError, so if something
really interesting happens, we'll still have something raised.
Also, I took that opportunity to show people that method definitions are implicit begin ... end blocks because, well, that's good to know. Essentially, the method could have just as easily been written like this and behaved the same way:
Code:
def find_first(name) $data_items.compact.select { |i| i.name[name] }.first.id rescue nilend# This works, too, but it's terribly verbose.def find_first(name) begin $data_items.compact.select { |i| i.name[name] }.first.id rescue nil endend