<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: Nemostultae's Code Snippets</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Fri, 29 Aug 2008 20:41:41 GMT</pubDate>
    <description>DZone Snippets: Nemostultae's Code Snippets</description>
    <item>
      <title>switch_around</title>
      <link>http://snippets.dzone.com/posts/show/995</link>
      <description>&lt;code&gt;&lt;br /&gt;require 'enumerator'&lt;br /&gt;&lt;br /&gt;# Returns an object of the argument's class with each_slice of 2 switched around.&lt;br /&gt;# Works on any object that mixes in #each&lt;br /&gt;# &lt;br /&gt;# Examples:&lt;br /&gt;# switch_around("foo!")       #=&gt; of!o&lt;br /&gt;# switch_around((1..10).to_a) #=&gt; [2, 1, 4, 3, 6, 5, 8, 7, 10, 9]&lt;br /&gt;def switch_around(data)&lt;br /&gt;  switched_data = data.class.new&lt;br /&gt;  &lt;br /&gt;  # When appending to a string ints will have #chr called on them, so protect against &lt;br /&gt;  # error about sending a message to nil. b will only be nil when the  collection is &lt;br /&gt;  # an odd length. Of course, this creates a bug. For example we could have an Array with &lt;br /&gt;  # embedded nils, so we must also check if it is a String (again...)&lt;br /&gt;  switch_proc = lambda do |a,b|&lt;br /&gt;    switched_data &lt;&lt; b unless b.nil? and data.is_a?(String)&lt;br /&gt;    switched_data &lt;&lt; a&lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;  # String#each enumerates over lines, so we must change it to enumerate over bytes.&lt;br /&gt;  if data.is_a?(String)&lt;br /&gt;    data.to_enum(:each_byte).each_slice(2) { |a,b| switch_proc.call(a, b) }&lt;br /&gt;  else&lt;br /&gt;    data.each_slice(2) { |a,b| switch_proc.call(a,b) }&lt;br /&gt;  end&lt;br /&gt;  &lt;br /&gt;  switched_data&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 21 Dec 2005 22:16:39 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/995</guid>
      <author>nemostultae (Daniel)</author>
    </item>
    <item>
      <title>each_slice</title>
      <link>http://snippets.dzone.com/posts/show/772</link>
      <description>&lt;code&gt;&lt;br /&gt;require 'enumerator'&lt;br /&gt;&lt;br /&gt;(1..10).each_slice(2) { |n| p n }&lt;br /&gt;# [1, 2]&lt;br /&gt;# [3, 4]&lt;br /&gt;# [5, 6]&lt;br /&gt;# [7, 8]&lt;br /&gt;# [9, 10]&lt;/code&gt;</description>
      <pubDate>Fri, 30 Sep 2005 16:50:45 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/772</guid>
      <author>nemostultae (Daniel)</author>
    </item>
  </channel>
</rss>
