= array_floe
== Overview
This small extension to ruby's Array class simplifies the reasonably-common
need to specially handle "floe"--i.e., first, last, odd, even--when
iterating through the elements of an array. It's particularly handy for
generating CSS classes.
Full Rdoc is available at http://rubydoc.info/gems/array_floe
== Usage
The gem provides two additional iterators, Array#each_with_floe and
Array#each_with_index_floe, that provide a "floe" object for each element
in the array:
ary.each_with_floe do |element, floe|
if floe.first?
puts "#{element} is the first element"
end
if floe.last?
puts "#{element} is the last element"
end
if floe.odd?
puts "#{element} is an odd-numbered element"
end
if floe.even?
puts "#{element} is an even-numbered element"
end
end
ary.each_with_index_floe do |element, i, floe|
assert_equal(i == 0, floe.first?)
assert_equal(i == ary.last, floe.last?)
assert_equal(i % 2 == 1, float.odd?)
assert_equal(i % 2 == 1, float.even?)
end
If no block is given, an enumerator is returned instead.
The "floe" object's to_s
method returns a space-separated list
of "first", "last", "odd", and "even" as appropriate:
[:a, :b, :c, :d].each_with_floe.collect{|element, floe| floe.to_s} #=> [ "first even", "odd", "even", "last odd" ]
floe.to_s
is particularly useful to construct CSS classes when generating HTML. For
example, this haml[http://haml-lang.com/] snippet:
%table
- [:a, :b, :c, :d].each_with_floe do |row, floe|
%tr{:class => floe}
%td= row
would yield this HTML snippet:
a |
b |
c |
d |