From: dblack@... Date: 2006-10-04T09:00:35+09:00 Subject: Re: Special variable within iterators to hold results? Hi -- On Wed, 4 Oct 2006, Timothy Goddard wrote: > > Wes Gamble wrote: >> I have this: >> >> FILTER_COLUMNS = Array.new >> DISPLAYABLE_COLUMNS.each do |field_array| >> FILTER_COLUMNS << [ field_array[1], field_array[0] ] >> end >> >> Is there any way to write this so that it could look something like: >> >> FILTER_COLUMNS = DISPLAYABLE_COLUMNS.each do |field_array| >> ??? << [ field_array[1], field_array[0] ] >> end >> >> so that I don't have to bother initializing FILTER_COLUMNS - is there >> some special variable that holds the intermediate result of the iterator >> body? >> >> Or perhaps an appropriate call to collect? >> > Firstly, you shouldn't capitalize your variables like that. Ruby will > treat any variable with a capital first letter as a constant - it will > behave differently. > > A better implementation would be: > > filter_columns = displayable_columns.map {|field_array| > [field_array[1], field_array[0]] > > or > > filter_columns = displayable_columns.map {|field_array| > field_array[0,2].reverse] You could also do: filter_columns = displayable_columns.map {|field_array| field_array.values_at(1,0) } David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org