Iterators

Posts tagged with "Iterators."
  • 31

    JAN
    2006

    Iterators (Chapters 4 and 5)

    Due to a printing error, these two chapters actually came out longer than intended. Originally their contents were: "Use Ruby."

    All jokes aside, there's really not a whole lot for me to talk about from these chapters, since iterators are so internal to Ruby. Readers from our camp should run into a lot less surprises here that the intended audience. Just translate MDJ's anonymous subroutines to blocks, replace his returns with yields, and you are 90% of the way there.

    Here are translations for some of the examples in these chapters. I think these all come out cleaner and more natural in Ruby, but you be the judge:

    Permutations

    #!/usr/local/bin/ruby -w
    
    def permute(items)
      0.upto(1.0/0.0) do |count|
        pattern = count_to_pattern(count, items.size) or break
        puts "Pattern #{pattern.join(' ')}:" if $DEBUG
        yield(pattern_to_permutation(pattern, items.dup))
      end
    end
    
    def pattern_to_permutation(pattern, items)
      pattern.inject(Array.new) { |results, i| results + items.slice!(i, 1) }
    end
    
    def count_to_pattern(count, item_count)
      pattern = (1..item_count).inject(Array.new) do |pat, i|
        pat.unshift(count % i)
        count /= i
        pat
      end
      count.zero? ? pattern : nil
    end
    
    if ARGV.empty?
      abort "Usage:  #{File.basename($PROGRAM_NAME)} LIST_OF_ITEMS"
    end
    
    permute(ARGV) { |perm| puts(($DEBUG ? "  " : "") + perm.join(" ")) }
    

    Read more…

  • 5

    JAN
    2006

    Code as a Data Type

    Introduction

    This is the first of a series of articles where I will try to demystify some Ruby idioms for the people who come to Ruby through Rails and find themselves wanting to learn a little more about the language under the hood.

    Strings, Arrays, ... and Code?

    You don't have to code for long in any language before you get intimately familiar with some standard data types. We all have a fair grasp of Ruby's String and Array, because every language has something similar. Ruby has an unusual data type though, which can trip up newcomers. That type is Ruby code itself.

    Allow me to explain what I mean, through an example. First, let's create a little in-memory database to work with:

    class ClientDB
      Record = Struct.new(:client_name, :location, :projects)
    
      def initialize
        @records = [ Record.new( "Gray Soft", "Oklahoma",
                                 ["Ruby Quiz", "Rails Extensions"] ),
                     Record.new( "Serenity Crew", "Deep Space",
                                 ["Ship Enhancements"] ),
                     Record.new( "Neo", "Hollywood", 
                                 ["Rails interface for the Matrix"] ) ]
      end
    end
    

    Read more…

  • 4

    JAN
    2006

    Pathname and Enumerator

    I'm always digging around in Ruby's standard library looking for new toys. It's one-stop-shopping for geeks. I love it.

    There really are some great tools in there that can help you do your work easier. Let me tell you a little about two I am using on a current application.

    Pathname

    Pop Quiz: Which would you rather work with?

    if File.exist? some_dir
      data = File.read( File.join( File.dirname(some_dir),
                                   "another_dir",
                                   File.basename(some_file) ) )
      # ...
    end
    

    Or:

    if some_dir.exist?
      data = (some_dir.dirname + "another_dir" + some_file.basename).read
      # ...
    end
    

    If you prefer the second version, the Pathname library is for you.

    Ruby's file manipulations are usually fine for normal work, but anytime I start messing with directories I really start feeling the pain. For that kind of work, I find Pathname to be a superior interface. My current project makes great use of the methods in the above example as well as Pathname#entries, Pathname#relative_path_from, and more.

    Read more…