Nested methods make me all DRY
Posted by Erik Peterson on 01/29/2008 20:00

Here's a cool little thing I ran into when investigating scoped_struct. You can nest methods on ruby:


  def a
    def b
      return "b"
    end
  end

That way, when you do a.b you get "b" as the result. Pretty neat, huh? This would be much more useful if you used it in classes to shorten up method names. Going with the example in Mike's blog, let's have a Player class that represents a football player. We want methods to give us some stats back:


  class Player
    def fumbles
      def dropped
        1
      end
      def lost
        2
      end
      def recovered
        3
      end
      self
    end
  end

This way, you get my_player.fumbles.dropped and my_player.fumbles.received all nested and defined all DRY like. One little catch is that you have to put that self return right after the method definitions in the fumbles scope. Otherwise, you'll get all kinds of nil errors.