Kyle X. wrote in post #990113:
First off thank you for the reply, and as you can probably tell I am
very novice at ruby >
No problem–that’s what this forum is for.
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
I’m using ruby 1.8.6 too, and the enumerator module is part of the ruby
standard library. Are you sure you spelled it right? But if it’s not
provided, it’s not provided.
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?
Yes, the each_slice() method allows you to chop up an array into chunks
of the specified size. Perhaps the simplest way to accomplish the same
thing in ruby 1.8.6 is using slice():
arr = [10, 20, 30, 40, 50]
results = []
while arr.size > 0
results << arr.slice!(0, 3) #(start_index, length)
end
p results
–output:–
[[10, 20, 30], [40, 50]]
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.
‘triplet’ is just a descriptive variable name. It is a “block
parameter” which is just like a method parameter:
def do_stuff(x) #x is a method parameter
x+2 #or you can explicitly write: return x+2
end
answer = do_stuff(5)
puts answer #=> 7
Ruby uses blocks everywhere. Here is a simple example:
words = [“hello”, “world”, “goodbye”]
words.each do |word|
puts word + “.”
end
–output:–
hello.
world.
goodbye.
The each() method sends each element of the array to the block, which is
this part:
do |word|
puts word
end
‘do’ signals the start of a block. What happens is that ruby calls the
block, which is like a method, for each element of the array. In
my example, the element of the array is assigned to the variable named
‘word’, and then inside the block you can do whatever you want to the
word variable.
The map() function, like each(), tells ruby to send each element of the
array to the block. However, map() also takes the return value of the
block and shoves it into a new array:
words = [“hello”, “world”, “goodbye”]
new_arr = words.map do |x|
1
end
p new_arr
–output:–
[1, 1, 1]
In that example, the block returns 1 for every element of the array.
But you can use map to do more useful things–like capitalize all the
words in the array:
words = [“hello”, “world”, “goodbye”]
new_arr = words.map do |x|
x.capitalize #same as: ‘return x.capitalize’
end
p new_arr
–output:–
[“Hello”, “World”, “Goodbye”]
So whenever, you want to do something to every member of an array and
save the results in a new_array, map()is a good choice.