<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users101</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/101" rel="self"/>
  <title>michiel</title>
  <updated>Tue Nov 06 01:48:23 -0800 2007</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor752</id>
    <published>2007-11-06T01:48:23-08:00</published>
    <title>[Ruby] On Print out the Regex Capture</title>
    <content type="html">

&lt;pre&gt;grep -o  regexp filename&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/133-print-out-the-regex-capture/refactors/752" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code125</id>
    <published>2007-11-01T01:42:07-07:00</published>
    <updated>2011-04-22T05:43:25-07:00</updated>
    <title>[Ruby] Base 62 Encoding</title>
    <content type="html">&lt;p&gt;Base WHAT??? Well, 62 is the number of alphanumeric characters. Base 64 makes more sense, but nobody can agree about what the two missing characters should be. &lt;/p&gt;

&lt;p&gt;Ruby's Numeric#to_s(base = 10) method works great, but won't accept a base above 36. Hence my implementation, which works, but is VERY VERY SLOW.&lt;/p&gt;

&lt;p&gt;Update: Rubinius actually does support base 62, and provides the c-code that does it: &lt;/p&gt;

&lt;p&gt;&lt;a href="http://www.google.com/codesearch?hl=en&amp;amp;q=+package" target="_blank"&gt;http://www.google.com/codesearch?hl=en&amp;amp;q=+package&lt;/a&gt;:%22&lt;a href="http://code.fallingsnow.net/svn/rubinius/trunk%22+mp_toradix_nd+show:8_qyRkJt6rs:_xHLAYhCNJI:gMCPZeygnhk" target="_blank"&gt;http://code.fallingsnow.net/svn/rubinius/trunk%22+mp_toradix_nd+show:8_qyRkJt6rs:_xHLAYhCNJI:gMCPZeygnhk&lt;/a&gt;&amp;amp;sa=N&amp;amp;cd=2&amp;amp;ct=rc&amp;amp;cs_p=http://code.fallingsnow.net/svn/rubinius/trunk&amp;amp;cs_f=shotgun/external_libs/libtommath/bn_mp_toradix_nd.c#first&lt;/p&gt;

&lt;p&gt;Seems like my algorithm is plenty fast, it's just Ruby being s.l.o.w.&lt;/p&gt;

&lt;pre&gt;SIXTYTWO = ('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a

def to_s_62(i)
  return '0' if i == 0
  s = ''
  while i &amp;gt; 0
    i,r = i.divmod(62)
    s = (SIXTYTWO[r]) + s
  end
  s
end
&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/125-base-62-encoding" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor617</id>
    <published>2007-10-28T18:35:45-07:00</published>
    <title>[Ruby] On String#to_proc (by Reginald Braithwaite)</title>
    <content type="html">&lt;p&gt;Ok, I've removed the nested ifs and I've introduced guards to quicky exit the method if possible. But I've made no attempt to parse the (uncommented) regular expressions, which do most of the actual work.&lt;/p&gt;

&lt;pre&gt;class String
  unless ''.respond_to?(:to_proc)
    def to_proc(&amp;amp;block)
      evaller = lambda {|ex| eval(ex, block &amp;amp;&amp;amp; block.binding) }
      prc_templ = lambda {|prm,ex| 'Proc.new { |' + prm.join(', ') + &amp;quot;| #{ex} }&amp;quot; }
      expr = self
      sections = expr.split(/\s*-&amp;gt;\s*/m).reverse
      return eval(sections.inject { |e, p| evaller[&amp;quot;(&amp;quot; + prc_templ[p.split(/\s/), e] + &amp;quot;)&amp;quot;] }) if sections.length &amp;gt; 1
      return evaller[prc_templ[['_'],expr]] if expr.match(/\b_\b/)
      params = []
      if expr.match(/^\s*(?:[+*\/%&amp;amp;|\^\.=&amp;lt;&amp;gt;\[]|!=)/m)
        params.push('$left')
        expr = '$left' + expr
      end
      if expr.match(/[+\-*\/%&amp;amp;|\^\.=&amp;lt;&amp;gt;!]\s*$/m)
        params.push('$right')
        expr += '$right'
      end
      if params.empty?
        x = self.gsub(/(?:\b[A-Z]|\.[a-zA-Z_$])[a-zA-Z_$\d]*|[a-zA-Z_$][a-zA-Z_$\d]*:|self|arguments|'(?:[^'\\]|\\.)*'|&amp;quot;(?:[^&amp;quot;\\]|\\.)*&amp;quot;/, '')
        x.scan(/([a-z_$][a-z_$\d]*)/i) {|v|  params.push(v) unless params.include?(v) }
      end
      evaller[prc_templ[params,expr]]
    end
  end
end&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/114-string-to_proc-by-reginald-braithwaite/refactors/617" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor528</id>
    <published>2007-10-24T11:15:32-07:00</published>
    <title>[Ruby] On Rubyize this : 4th edition</title>
    <content type="html">&lt;p&gt;Building on Mark Van Holstyn's solution, keeping the 'keep_spiders' syntax and cleaner syntax for entering bugs.&lt;/p&gt;

&lt;pre&gt;require 'rubygems'
require 'active_support'

MSG = &amp;quot;I am a %s and my name is %s. I have an IQ of %s and an annoyance factor of %s&amp;quot;

class Bug &amp;lt; Struct.new(:type, :desc)
  alias to_s desc
end

class Bugs &amp;lt; Array
  def method_missing(name, *_)
    return super unless name.to_s =~ /^keep_/
    Bugs.new(select { |bug| bug.type.to_s == name.to_s[5..-1].singularize })
  end
end

def make_bugs(bugs = Bugs.new)
  yield lambda {|*a| bugs &amp;lt;&amp;lt; Bug.new(a[1], sprintf(MSG, *a)) }
end

bugs = make_bugs do |bug|
  bug[&amp;quot;ron&amp;quot;,    :spider,       4,  2]
  bug[&amp;quot;don&amp;quot;,    :spider,       2,  3]
  bug[&amp;quot;jake&amp;quot;,   :ant,          9,  4]
  bug[&amp;quot;chris&amp;quot;,  :ladybug,      2,  4]
  bug[&amp;quot;fred&amp;quot;,   :cockchaffer,  0,  5]
  bug[&amp;quot;greg&amp;quot;,   :butterfly,    2,  0]
  bug[&amp;quot;jason&amp;quot;,  :butterfly,    0,  2]
end

puts bugs.keep_butterflies&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/99-rubyize-this-4th-edition/refactors/528" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor509</id>
    <published>2007-10-23T11:33:10-07:00</published>
    <title>[Ruby] On Argument eval</title>
    <content type="html">&lt;p&gt;And you don't use &amp;quot;eval&amp;quot; because you don't trust the caller? What does &amp;quot;line_eval&amp;quot; do?
&lt;br /&gt;Also, use &amp;quot;scan&amp;quot; to break up the entire line in tokens (square brackets, commas, =&amp;gt; and others).
&lt;br /&gt;You could even use something like Racc (&lt;a href="http://i.loveruby.net/en/projects/racc/doc/" target="_blank"&gt;http://i.loveruby.net/en/projects/racc/doc/&lt;/a&gt;) to generate a parser for you. Overkill, I know, but a nice exercise, and with only four tokens it can't be hard.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/98-argument-eval/refactors/509" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code83</id>
    <published>2007-10-14T10:57:52-07:00</published>
    <updated>2007-10-15T14:18:13-07:00</updated>
    <title>[Ruby] Combinatorial explosion with continuations</title>
    <content type="html">&lt;p&gt;This code tries to find all variations of an English sentence produced by contracting pronouns and modal verbs.&lt;/p&gt;

&lt;p&gt;To see what it does, just run it, or look at the assertions at the bottom.&lt;/p&gt;

&lt;p&gt;It's a fragment of a problem that my start-up has. I'm trying to collect all translations of a given sentence, and suddenly a previously trivial method turns out to have more than one possible answer in one edge case, and I have to go on a huge refactoring spree to accomodate that.&lt;/p&gt;

&lt;p&gt;I'm now exploring a general solution that uses continuations. I hope this will it easier to add new rules to my code.&lt;/p&gt;

&lt;p&gt;Can you do it cleaner? Using &amp;quot;amb&amp;quot;? Without the global variable? Shorter and without continuations? Using a list monad? Using other techniques?&lt;/p&gt;

&lt;pre&gt;$c = []
def fork_reality(*l)
  callcc {|c| $c &amp;lt;&amp;lt; c }
  $c.pop if l.size &amp;lt;= 1
  l.shift
end

def collect_realities
  $c.last.call until $c.empty?
end

def contract_sentence(arr, index = 0, res = [])
  return res.compact.join(' ') if index == arr.size 
  skip = 1
  x = arr[index]
  nxt = arr[index+1]
  nxt2 = arr[index+2]
  r = case
  when x == 'a' &amp;amp;&amp;amp; (nxt =~ /^[aeiuo]/ || nxt =~ /^hono/ || nxt =~ /^honest/ || nxt =~ /^hour/)
    'an'
  when x == 'I' &amp;amp;&amp;amp; nxt == 'am'
    skip = 2
    fork_reality(&amp;quot;I'm&amp;quot;, &amp;quot;I am&amp;quot;)
  when %w(you we they).include?(x) &amp;amp;&amp;amp; %w(are have).include?(nxt) &amp;amp;&amp;amp; nxt2 == 'not'
    skip = 3
    fork_reality(&amp;quot;#{x}'#{nxt[-2,2]} not&amp;quot;, &amp;quot;#{x} #{nxt}n't&amp;quot;, &amp;quot;#{x} #{nxt} not&amp;quot;)
  when %w(you we they).include?(x) &amp;amp;&amp;amp; %w(are have).include?(nxt)
    skip = 3
    fork_reality(&amp;quot;#{x}'re&amp;quot;, &amp;quot;#{x} #{nxt}&amp;quot;)
  when %w(he she it).include?(x) &amp;amp;&amp;amp; %w(is has).include?(nxt) &amp;amp;&amp;amp; nxt2 == 'not'
    skip = 3
    fork_reality(&amp;quot;#{x} #{nxt}n't&amp;quot;, &amp;quot;#{x} #{nxt} not&amp;quot;)
  when %w(he she it).include?(x) &amp;amp;&amp;amp; %w(is has).include?(nxt)
    skip = 2
    fork_reality(&amp;quot;#{x}'s&amp;quot;, &amp;quot;#{x} #{nxt}&amp;quot;)
  when %w(is are).include?(x) &amp;amp;&amp;amp; nxt == 'not'
    skip = 2
    fork_reality(&amp;quot;#{x}n't&amp;quot;, &amp;quot;#{x} #{nxt}&amp;quot;)
  else
    x
  end
  contract_sentence(arr, index + skip, res + [r])
end

r = []

r &amp;lt;&amp;lt; contract_sentence(%w(I am green but you are not white and Bob is not a honest man while Alice and Ina are not purple))

collect_realities

raise unless r.include? &amp;quot;I'm green but you aren't white and Bob isn't an honest man while Alice and Ina aren't purple&amp;quot;
raise unless r.include? &amp;quot;I'm green but you are not white and Bob is not an honest man while Alice and Ina are not purple&amp;quot;
raise unless r.include? &amp;quot;I am green but you are not white and Bob is not an honest man while Alice and Ina aren't purple&amp;quot;

p r&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/83-combinatorial-explosion-with-continuations" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor389</id>
    <published>2007-10-12T01:37:47-07:00</published>
    <title>[Ruby] On Iffy</title>
    <content type="html">&lt;p&gt;YAML solutions break down when the text isn't static. I use procs:&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;

&lt;pre&gt;# in helper 

  TIME_REMAINING_TODAY =  {
   :en =&amp;gt; &amp;quot;%s of practice remaining today&amp;quot;,
   :nl =&amp;gt; &amp;quot;nog %s te oefenen vandaag&amp;quot;,
   :de =&amp;gt; &amp;quot;noch %s zu &#195;&#188;ben heute&amp;quot;,
   :fr =&amp;gt; &amp;quot;encore %s de pratique aujourd'hui&amp;quot;,
  }
  define_message :time_remaining_today do |time, lang|
    sprintf(TIME_REMAINING_TODAY[lang], i_distance_of_time_in_words(time, lang))
  end

# in model  (doesn't know or care about user language)
return time_remaining_today(interval)

# in controller
@msg = model.calc_time

# in view

&amp;lt;%= @msg[@user.lang] %&amp;gt;
&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/75-iffy/refactors/389" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor315</id>
    <published>2007-10-07T16:28:11-07:00</published>
    <title>[Ruby] On is_prime?</title>
    <content type="html">&lt;p&gt;Looks good, David! One nitpick is that since you know the size of the array, it's faster to initialize it with that size. I'd leave is_prime? undefined for 0 and 1.&lt;/p&gt;

&lt;pre&gt;primes = Array.new(nil, ceiling + 1)
&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/40-is_prime/refactors/315" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor300</id>
    <published>2007-10-05T13:43:33-07:00</published>
    <title>[Ruby] On Random number generator</title>
    <content type="html">&lt;p&gt;You know, rand(x) doesn't return anything but numbers either - why bother doing it one character at the time?&lt;/p&gt;

&lt;pre&gt;(1..500).map {rand(10 ** 16).to_s.rjust(16,'0')}&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/47-random-number-generator/refactors/300" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor298</id>
    <published>2007-10-05T09:31:56-07:00</published>
    <title>[Ruby] On Recursively convert multidimensional structure's values to string</title>
    <content type="html">&lt;p&gt;In your inner loop, i == a[:hash][a[:hash].index(i)].&lt;/p&gt;

&lt;pre&gt;# Converts:
# {:hash =&amp;gt; [{:foo =&amp;gt; 1}, {:foo =&amp;gt; 2}]}
# 
# To:
# {:hash =&amp;gt; [{:foo =&amp;gt; &amp;quot;1&amp;quot;}, {:foo =&amp;gt; &amp;quot;2&amp;quot;}]}

a[:hash].each do |i| 
  i.each do |key,value| 
    i[key] = value.to_s
  end
end&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/64-recursively-convert-multidimensional-structure-s-values-to-string/refactors/298" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor282</id>
    <published>2007-10-04T15:47:54-07:00</published>
    <title>[Ruby] On Looking for alphabetized place in array set</title>
    <content type="html">&lt;p&gt;The previous refactoring is great. Just let the db do the work. Staying closer to the original, it could be a lot leaner. Don't bother with breaks, just return when you've found your match. If the first child's name &amp;gt; than the cat_name, there's no match. If you haven't found anything after the loop, it's the last child, if there are any children. 
&lt;br /&gt;You can you inject to keep track of 'left' - you seed it with &amp;quot;inject(nil)&amp;quot; - the last expression becomes &amp;quot;left&amp;quot; in the next iteration, and you store the final iteration in the &amp;quot;left&amp;quot; local variable.
&lt;br /&gt;has_many relations don't return nil - no need to check. And &amp;quot;unless !&amp;quot; is better known as &amp;quot;if&amp;quot;.&lt;/p&gt;

&lt;p&gt;Cheers,&lt;/p&gt;

&lt;p&gt;Michiel.&lt;/p&gt;

&lt;pre&gt;def self.find_left_sibling( parent_id, cat_name )
    parent = Category.find( :first, 
                            :conditions =&amp;gt; [ &amp;quot;id = ?&amp;quot;, parent_id] )
    left = parent.children.inject(nil) do |left,child|
      return left &amp;amp;&amp;amp; left.id if cat_name &amp;lt; child.name
      child
    end 
    left &amp;amp;&amp;amp; left.id
end&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/57-looking-for-alphabetized-place-in-array-set/refactors/282" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code56</id>
    <published>2007-10-04T04:55:34-07:00</published>
    <updated>2007-10-04T04:55:34-07:00</updated>
    <title>[Ruby] Enforcing bounds</title>
    <content type="html">&lt;p&gt;Given a value and a range, I want to the value, unless it falls outside the range. In that case I want to return the lower or upper bound. Is there a more readable solution which does not involve creating new methods?&lt;/p&gt;

&lt;pre&gt;x &amp;lt; lower ? lower : x &amp;gt; upper ? upper : x

# Or should I just go this way:
# class Range; def %(x); x &amp;lt; first ? first : x &amp;gt; last ? last : x ; end ; end
# (0..5) % x&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/56-enforcing-bounds" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor259</id>
    <published>2007-10-03T18:52:27-07:00</published>
    <title>[Ruby] On Show a default value if object or field is empty?</title>
    <content type="html">&lt;p&gt;The original solution is fine, except for calling the block twice instead of caching the result. BTW, why test using object.nil? and not just using !object ? Do you really except false values for object?&lt;/p&gt;

&lt;pre&gt;def show_value_or_default(object, default = &amp;quot;-&amp;quot;)
  return default if object.nil?
  tmp = yield(object)  
  tmp.blank? ? default : tmp 

  # or as a single expression
  # (object.nil? || (tmp = yield(object)).blank?) ? default : tmp
end&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/50-show-a-default-value-if-object-or-field-is-empty/refactors/259" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor184</id>
    <published>2007-10-01T19:55:40-07:00</published>
    <title>[Ruby] On is_prime?</title>
    <content type="html">&lt;p&gt;This is a concise implementation of Fermat's Little Theorem. But don't run it because it is really slow. You need an algorithm to calculate a^p % p without actually calculating a^p, since a == 47 and p == 100000 in this example. You can probably find it in Knuth, second volume.&lt;/p&gt;

&lt;pre&gt;class Integer
  PR = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
  def is_prime?
    PR.all? {|x| x ** self % self == x}
  end
end

# don't run&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/40-is_prime/refactors/184" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor183</id>
    <published>2007-10-01T19:40:35-07:00</published>
    <title>[Ruby] On is_prime?</title>
    <content type="html">&lt;p&gt;This is equally long, and 20% faster. Not as elegant as Fermat's Little Theorem, but I don't know how many tests you need to get acceptable accuracy.&lt;/p&gt;

&lt;pre&gt;require 'benchmark'
include Math

GC.disable

PR = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
class Integer
  def is_prime?
    return PR.include?(self) if self &amp;lt; 53
    PR.each {|y| return false if self % y == 0 }
    i = 53
    ss = sqrt(self).floor
    while i &amp;lt;= ss
      return false if self % i == 0
      i += 2
    end
    true
  end
end

# test it
primes = []
puts Benchmark.realtime{(1..100000).each{|x|primes &amp;lt;&amp;lt; x if x.is_prime?}}
puts primes.size
&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/40-is_prime/refactors/183" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor166</id>
    <published>2007-10-01T13:18:03-07:00</published>
    <title>[Ruby] On Random pronouncable password</title>
    <content type="html">&lt;p&gt;There is duplication in the list of consonants, and the method does uppercase too. Plus, Array should really have *pick* (rails 2.0 has it, but they call it *rand*).&lt;/p&gt;

&lt;pre&gt;class Array
  def pick
    at rand(size)
  end
end

def random_pronouncable_password(size=4)
  v = %w(a e i o u y)
  c = ('a'..'z').to_a - v - ['q'] + %w(qu ch cr fr nd ng nk nt ph pr rd sh sl sp st th tr)
  (1..size).map{[c.pick, v.pick]}.flatten.map{|x| [x,x.upcase].pick}.join('')
end&lt;/pre&gt;</content>
    <author>
      <name>michiel</name>
      <email>merloen@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/3-random-pronouncable-password/refactors/166" rel="alternate"/>
  </entry>
</feed>

