result = [2, 4, 1, 3, 5, 6, 8].chunk do |num|
  num.even?
end

result.each do |even_result, a_chunk|
  p [even_result, a_chunk]
end

--output:--
[true, [2, 4]]
[false, [1, 3, 5]]
[true, [6, 8]]


====

e = DATA.chunk do |line|
  ascii_code_for_first_letter = line.ord
end

e.each do |ascii_code, lines|
  character = ascii_code.chr
  number_of_lines_in_array = lines.length
  p [character, number_of_lines_in_array]
end

__END__
a
ant
apple
ball
basket
cake
aztec


--output:--
["a", 3]
["b", 2]
["c", 1]
["a", 1]


Note that a dictionary file would not have that last line--all the 'a' 
words would be grouped together.


As for your last example, the chunk() docs say this:

====
The following key values has special meaning:

nil .... specifies that the elements are dropped.
===

If you look at the first example in my post, the elements that fail the 
test are chunked into a separate group.   However, the test in the log 
file example is written like this:

line != sep || nil

which is equivalent to:

(line != sep) || nil

If the line in the file is a bunch of dashes, the the test on the left 
fails because line is equal to sep.  Next, in an or statement:

 something || something

if the left side is true, then ruby doesn't even execute the right 
side--because an OR is true if either side of the OR is true.  No matter 
what the right side evaluates to, the OR will be true if the left side 
is true, so ruby skips the right side if the left side evaluates to 
true.  ruby then returns the value of the left side.

So if the line in the file equals a bunch of dashes, then the left side 
test fails, and so the right side is evaluated and returned.

Terrible docs, I would say.

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

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to