This one post won’t be particularly about Ruby on Rails but a Ruby itself. But since, let’s just say Ruby on Rails ‘benefits’ from Ruby I thought it would be nice to share with other Ruby on Rails developers about new ways of hacking things in Rails, running on Ruby 1.9.2 of course.
Actually it’s pretty fun. We got a whole new set of methods we can use in our Ruby on Rails projects while playing with Arrays. As we can read in NEWS file:

  • Array
    • new methods:
      • Array#keep_if
      • Array#repeated_combination
      • Array#repeated_permutation
      • Array#rotate
      • Array#rotate!
      • Array#select!
      • Array#sort_by!
    • extended methods:
      • Array#{uniq,uniq!,product} can take a block.
  • Enumerable
    • new methods:
      • Enumerable#chunk
      • Enumerable#collect_concat
      • Enumerable#each_entry
      • Enumerable#flat_map
      • Enumerable#slice_before

Let’s demonstrate two most interesting example that could find it’s use in everyday Ruby on Rails programming.

slice_before
%w|Ruby on Rails 2 is older than Ruby on Rails 3 bet you didn’t know that|.slice_before(/\d/).to_a
#=> [["Ruby", "is", “Rails”], ["2", "is", "older", “than”, “Ruby”, “on”, “Rails” ], ["3", "bet", "you", "didn’t", “know”, “that”]
 
# a more complex version from the docs (slightly modified):
a = [0,2,3,4,6,7,9]
prev = a[0]
a.slice_before {|cur|
 prev, prev2 = cur, prev  # one step further
 prev2 + 1 != prev        # two ago != one ago ? --> new slice
}.to_a
# => [[0], [2, 3, 4], [6, 7], [9]]
 
chunk
 
(1..20).chunk{|n| n%5 == 0}.each{|result, elements|
 puts "#{result}: #{elements*' - '}"
}
# outputs:
# false: 1 - 2 - 3 - 4
# true: 5
# false: 6 - 7 - 8 - 9
# true: 10
# false: 11 - 12 - 13 - 14
# true: 15
# false: 16 - 17 - 18 - 19
# true: 20
<a href="http://rubyonrailsdevelopment.pl/wp-content/uploads/2010/07/twitter-avatar_bigger.png"><img class="alignnone size-full wp-image-664" title="twitter-avatar_bigger" src="http://rubyonrailsdevelopment.pl/wp-content/uploads/2010/07/twitter-avatar_bigger.png" alt="Uruguay Ruby on Rails conference logo" width="73" height="73" /></a>

Just refer to docs if you want more. It would be nice to be well prepared for incoming Ruby 1.9.2 and Ruby on Rails 3.