title: First Class Functions In Ruby
body: <p>I am working my way through this article on functional programming (<a href="https://codewords.recurse.com/issues/one/an-introduction-to-functional-programming" rel="nofollow">https://codewords.recurse.com/issues/one/an-introduction-to-functional-programming</a>) and trying to do the exercises in Ruby. </p>
  
  <p>One exercise defines two functions, zero and one. Zero takes a string parameter and returns string index 1 - end if the first character is 0, One does the same thing but only if the first character is one.</p>
  
  <p>Here are the ruby implementations: </p>
  
  <pre><code>def zero(s)
    if s[0] == "0"
      return s[1..(s.length)]
    end
  end
  
  def one(s)
    if s[0] == "1"
      return s[1..(s.length)]
    end
  end
  </code></pre>
  
  <p>The problem asks you to write a method called rule_sequence that, given a string and an array of functions, returns the result such that the functions are invoked one at a time -- the first function is invoked in the whole string, the second function invoked on the return value of that string, etc. If, at any point, the one of the functions returns nil, return nil. </p>
  
  <p>The Python implementation is: </p>
  
  <pre><code>def rule_sequence(s, rules):
      if s == None or not rules:
          return s
      else:
          return rule_sequence(rules[0](s), rules[1:])
  </code></pre>
  
  <p>However, since it doesn't seem like Ruby has support for higher order functions, the most elegant solution I could come up with was the following:</p>
  
  <pre><code>def rule_sequence(string, rules)
    if rules.length == 0 or string.nil?
      return string
    else
      return rule_sequence(rules[0].call(string), rules[1..rules.length])
    end
  end
  
  puts rule_sequence('0101', [lambda { |s| zero(s) }, lambda { |s| one(s) }, lambda { |s| zero(s) } ])
  </code></pre>
  
  <p>Can anyone come up with something more terse than passing or calling lambdas?</p>