[Rails] Re: Problem with select and each_with_index

Chris T chrismtaggart at yahoo.co.uk
Wed Mar 1 09:49:33 GMT 2006


>>>>> <option value="B">B</option>
>>>>> <option value="C">C</option>
>>>>> <option value="D">D</option></select>
>>>> 
>>>> each_with_index just evaluates to its argument.  Instead you need
>>>> to build and return a new array.  Something like this should work:
>>>> 
>>>> Typecategory.inject([]) { |options, item| options << [item, 
>>>> options.size] }
>>> Mark

> 
> Thinking about this again and re-reading your email, think I'm beginning 
> to see the light. If I'm understanding it correctly, the fact that
> <%= select ('type', 'typecategory', Typecategory.each {|type| type} )%>
> produce a select box feating Typecategory elements is nothing to do with 
> each runnning through the elements, it's just acting on Typecategory. In 
> fact whatevery enumerations are done on typecategory will not change 
> what comes out (cue dim light-bulb being switched on).

Also [understanding even better after good night's sleep -- and just in 
case anyone else has same problem]:
<%= select ('type', 'typecategory', Typecategory.each {|type| type} )%> 
might as well be written:
<%= select ('type', 'typecategory', Typecategory)%> because select is 
looking for an array and as RDoc explains (when you read it properly):

array.each {|item| block } → array # thus returning the original array 
whereas:

enum.inject {| memo, obj | block } => obj

gives you a new array (object). Proper understanding at last.

-- 
Posted via http://www.ruby-forum.com/.


More information about the Rails mailing list