small medium large xlarge

Generic-user-small
03 Aug 2008, 04:43
Tan YL (19 posts)
state_lookup = us_states.index_by { state state.short_name} what exactly is state supposed to repressent? why do we need to to call the object again? doesn’t rails understand that state.short_name will come from state? I thought rails was trying to eliminate redundancy.
Samr_small_pragsmall
03 Aug 2008, 11:47
Sam Ruby (634 posts)

Ruby blocks are described briefly in section A.9. The statement above combines a number of powerful Ruby constructs.

A block is a form of a procedure or function. In this case what is between the curly braces is a function with one argument. This function, given one argument which it calls state, will return state.short_name.

index_by is a method that will take each element of an Enumerable (in this case an array) and convert it into a hash element with a key provided by calling the block provided, and the original enumeration element as the value.

Put it all together, and you get roughly the following:

“for each element in us_states, take an element and temporarily bind it to the name state and then form a hash element using this value according to the following expression: {state.short_name => state}. Merge the results together and store the result in state_lookup”.

Generic-user-small
03 Aug 2008, 12:38
Tan YL (19 posts)

ok thx. I kinda get it now.

You must be logged in to comment