views:

71

answers:

2

Look at the discussion on this thread . I am not able to follow how having a block to a fetch is a better solution.

+5  A: 

In the first patch on Rails ticket #4558:

options.fetch(:alt, File.basename(src, '.*').capitalize)

This line executes the basename and capitalize functions and then passes the result into Hash#fetch regardless of if a value for :alt already exists in the options hash.

In the updated patch:

options.fetch(:alt) { File.basename(src, '.*').capitalize }

The same basename/capitalize code is only executed when Hash#fetch needs the default value (i.e. when the :alt key does not exist in the options hash). This means the (possibly expensive) calculation of the default value can be skipped if it's not needed.

See the documentation on Hash#fetch for more details.

Jason Weathered
I thought that was the case but I guess my test was not a good one. Since the result was same in both the cases and thus I got confused. Thanks.
Nadal
A: 

I don't know what duck-punching Rails has been doing to Hash#fetch, but with Plain Old Ruby Objects, I use it rather than Hash#[] because when I ask for something and it's not available, I want to know about it. This is called "Failing early" (or "Crashing early" in The Pragmatic Programmer's List of Tips)

Andrew Grimm