From: Robert Klemme Date: 2011-03-31T17:11:49+09:00 Subject: Re: How can I generate new variables? On Thu, Mar 31, 2011 at 5:08 AM, Kyle X. wrote: > First off thank you for the reply, and as you can probably tell I am > very novice at ruby ><. However I am running into a few issues with > this. > >> Using arrays.  An array can contain anything--including other arrays: >> >> >> require 'enumerator'  #not necessary in ruby 1.9 >> >> master_arr = [] >> data = [1, 2, 3,  4, 5, 6,  7, 8] >> >> data.each_slice(3) do |triplet| >>   master_arr << triplet >> end >> >> p master_arr >> >> --output:-- >> [[1, 2, 3], [4, 5, 6], [7, 8]] > > I am writing this for SketchUP so I am using Ruby 1.8.6 and am having an > issue with require 'enumerator', as it does not exist in their library > as far as I can tell --- in turn the "each_slice" command does not > function. You can easily cook it yourself module Enumerable def each_slice(n) a = [] each do |x| a << x if a.size == n yield a a.clear end end yield a unless a.empty? self end end > I was wondering if you could help me understand this command better as > well.  "data.each_slice(3) do |triplet|"  The "(3)" here means slice > after 3 entries in data correct? Correct. >  The word triplet used, is this word > required or could it be any word as long as it is consistent below i.e. > :  do |x| master_arr << x?  Sorry for the basic question, but I just > want to clarify. Yes, it's the name of the block argument. You can name it anyway you like. You should only avoid reusing a name used outside the block in order to avoid confusion and incompatibility should the program be executed on 1.9 at one day. You can even use three names! irb(main):041:0> Array.new(10) {|idx| idx} => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] irb(main):042:0> Array.new(10) {|idx| idx}.each_slice(3) {|first,second,third| p first} 0 3 6 9 => nil > The rest I think I have figured out, but still not 100% on the map > function. Enumerable#map sends all values through a conversion function and collects them in a new Array: irb(main):043:0> Array.new(10) {|idx| idx}.map {|x| x + 100} => [100, 101, 102, 103, 104, 105, 106, 107, 108, 109] Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/