Skip to content
Douglas G. Allen edited this page Jan 31, 2015 · 2 revisions

Home

module Enumerable examples

#--------------------------------------------------------------------
    %w{ant bear cat}.all? {|word| word.length >= 3}   #=> true
    %w{ant bear cat}.all? {|word| word.length >= 4}   #=> false
    [ nil, true, 99 ].all?                            #=> false
#--------------------------------------------------------------------
    %w{ant bear cat}.any? {|word| word.length >= 3}   #=> true
    %w{ant bear cat}.any? {|word| word.length >= 4}   #=> true
    [ nil, true, 99 ].any?                            #=> true
#--------------------------------------------------------------------
    [3,1,4,1,5,9,2,6,5,3,5].chunk {|n| n.even?}.each {|even, ary| p [even, ary]}

    open("/usr/share/dict/words", "r:iso-8859-1") {|f|
      f.chunk {|line| line.ord }.each {|ch, lines| p [ch.chr, lines.length] }
    }

    sep = "-"*72 + "\n"
    IO.popen("svn log README") {|f|
      f.chunk {|line|
        line != sep || nil
      }.each {|_, lines|
      pp lines
      }
    }

    File.foreach("README").chunk {|line|
      /\A\s*\z/ !~ line || nil
      }.each {|_, lines|
      pp lines
    }

    pat = /\A[A-Z][A-Za-z0-9_]+\#/
    open(filename) {|f|
      f.chunk {|line| pat =~ line ? $& : :_alone }.each {|key, lines|
        if key != :_alone then
          print lines.sort.join('')
        else
          print lines.join('')
        end
      }
    }
#----------------------------------------------------------------------
    (1..4).collect {|i| i*i }   #=> [1, 4, 9, 16]
    (1..4).collect { "cat"  }   #=> ["cat", "cat", "cat", "cat"]
#----------------------------------------------------------------------
    [[1,2],[3,4]].collect_concat {|i| i }   #=> [1, 2, 3, 4]
#----------------------------------------------------------------------
    [1, 2, 4, 2].count             #=> 4
    [1, 2, 4, 2].count(2)          #=> 2
    [1, 2, 4, 2].count{|x|x%2==0}  #=> 3
#-----------------------------------------------------------------------
    ["a", "b", "c"].cycle {|x| puts x }     # print, a, b, c, a, b, c,.. forever.
    ["a", "b", "c"].cycle(2) {|x| puts x }  # print, a, b, c, a, b, c.
#---------------------------------------------------------------------
    (1..10).detect  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
    (1..100).detect {|i| i % 5 == 0 and i % 7 == 0 }   #=> 35
#-----------------------------------------------------------------------
   [1, 2, 3, 4, 5, 0].drop(3)             #=> [4, 5, 0]
#-----------------------------------------------------------------------
   [1, 2, 3, 4, 5, 0].drop_while {|i| i < 3 }   #=> [3, 4, 5, 0]
#-----------------------------------------------------------------------
    (1..10).each_cons(3) {|a| p a}
#---------------------------------------------------------------------
    class Foo
      include Enumerable
      def each
        yield 1
        yield 1,2
        yield
      end
    end
    Foo.new.each_entry{|o| p o }
#---------------------------------------------------
    (1..10).each_slice(3) {|a| p a}
#---------------------------------------------
    hash = Hash.new
    %w(cat dog wombat).each_with_index {|item, index|
      hash[item] = index
    }
    hash   #=> {"cat"=>0, "dog"=>1, "wombat"=>2}
#------------------------------------------------------
    evens = (1..10).each_with_object([]) {|i, memo| memo << i*2 }
#--------------------------------------------------------------------
    (1..7).entries                       #=> [1, 2, 3, 4, 5, 6, 7]
    { 'a'=>1, 'b'=>2, 'c'=>3 }.entries   #=> [["a", 1], ["b", 2], ["c", 3]]
#------------------------------------------------------------------------------
    (1..10).find  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
    (1..100).find {|i| i % 5 == 0 and i % 7 == 0 }   #=> 35
#------------------------------------------------------------------
    (1..10).find_all {|i|  i % 3 == 0 }   #=> [3, 6, 9]
#----------------------------------------------------------------
    (1..10).find_index  {|i| i % 5 == 0 and i % 7 == 0 }   #=> nil
    (1..100).find_index {|i| i % 5 == 0 and i % 7 == 0 }   #=> 34
    (1..100).find_index(50)                                #=> 49
#------------------------------------------------------------------
    %w[foo bar baz].first     #=> "foo"
    %w[foo bar baz].first(2)  #=> ["foo", "bar"]
    %w[foo bar baz].first(10) #=> ["foo", "bar", "baz"]
    [].first                  #=> nil
#-----------------------------------------------------------
   [[1,2],[3,4]].flat_map {|i| i }   #=> [1, 2, 3, 4]
#-------------------------------------------------------------
    (1..100).grep 38..44   #=> [38, 39, 40, 41, 42, 43, 44]
    c = IO.constants
    c.grep(/SEEK/)         #=> [:SEEK_SET, :SEEK_CUR, :SEEK_END]
    res = c.grep(/SEEK/) {|v| IO.const_get(v) }
    res                    #=> [0, 1, 2]
#------------------------------------------------------------------
    (1..6).group_by {|i| i%3}   #=> {0=>[3, 6], 1=>[1, 4], 2=>[2, 5]}
#----------------------------------------------------------------------
    IO.constants.include? :SEEK_SET          #=> true
    IO.constants.include? :SEEK_NO_FURTHER   #=> false
#--------------------------------------------------------------------
    # Sum some numbers
    (5..10).inject(:+)                            #=> 45

    # Same using a block and inject
    (5..10).inject {|sum, n| sum + n }            #=> 45

    # Multiply some numbers
    (5..10).inject(1, :*)                         #=> 151200

    # Same using a block
    (5..10).inject(1) {|product, n| product * n } #=> 151200

    # find the longest word
    longest = %w{ cat sheep bear }.inject do |memo,word|
       memo.length > word.length ? memo : word
    end
    longest                                       #=> "sheep"
#------------------------------------------------------------------
    (1..4).collect {|i| i*i }   #=> [1, 4, 9, 16]
    (1..4).collect { "cat"  }   #=> ["cat", "cat", "cat", "cat"]
#----------------------------------------------------------------
    %w(albatross dog horse).max                                  #=> "horse"
    %w(albatross dog horse).max {|a,b| a.length <=> b.length }   #=> "albatross"
#------------------------------------------------------------------------------------
    %w(albatross dog horse).max_by {|x| x.length }   #=> "albatross"
#------------------------------------------------------------------------
    IO.constants.member? :SEEK_SET          #=> true
    IO.constants.member? :SEEK_NO_FURTHER   #=> false
#---------------------------------------------------------
    %w(albatross dog horse).min                                  #=> "albatross"
    %w(albatross dog horse).min {|a,b| a.length <=> b.length }   #=> "dog"
#------------------------------------------------------------------------------
    %w(albatross dog horse).min_by {|x| x.length }   #=> "dog"
#-----------------------------------------------------------------
    %w(albatross dog horse).minmax                                  #=> ["albatross", "horse"]
    %w(albatross dog horse).minmax {|a,b| a.length <=> b.length }   #=> ["dog", "albatross"]
#---------------------------------------------------------------------------------------------
    %w(albatross dog horse).minmax_by {|x| x.length }   #=> ["dog", "albatross"]
#------------------------------------------------------------------------------------
    %w{ant bear cat}.none? {|word| word.length == 5}  #=> true
    %w{ant bear cat}.none? {|word| word.length >= 4}  #=> false
    [].none?                                          #=> true
    [nil].none?                                       #=> true
    [nil,false].none?                                 #=> true
#--------------------------------------------------------------------
    %w{ant bear cat}.one? {|word| word.length == 4}   #=> true
    %w{ant bear cat}.one? {|word| word.length > 4}    #=> false
    %w{ant bear cat}.one? {|word| word.length < 4}    #=> false
    [ nil, true, 99 ].one?                            #=> false
    [ nil, true, false ].one?                         #=> true
#-----------------------------------------------------------------
    (1..6).partition {|v| v.even? }  #=> [[2, 4, 6], [1, 3, 5]]
#-----------------------------------------------------------------
    # Sum some numbers
    (5..10).reduce(:+)                            #=> 45

    # Same using a block and inject
    (5..10).reduce {|sum, n| sum + n }            #=> 45

    # Multiply some numbers
    (5..10).reduce(1, :*)                         #=> 151200

    # Same using a block
    (5..10).reduce(1) {|product, n| product * n } #=> 151200

    # find the longest word
    longest = %w{ cat sheep bear }.reduce do |memo,word|
       memo.length > word.length ? memo : word
    end
    longest                                       #=> "sheep"
#--------------------------------------------------------------
    (1..10).reject {|i|  i % 3 == 0 }   #=> [1, 2, 4, 5, 7, 8, 10]
#-------------------------------------------------------------------
    (1..3).reverse_each {|v| p v }
#------------------------------------------------------
    (1..10).select {|i|  i % 3 == 0 }   #=> [3, 6, 9]
#--------------------------------------------------------
    open("ChangeLog") {|f|
      f.slice_before(/\A\S/).each {|e| pp e}
    }

    open("ChangeLog") {|f|
      f.slice_before {|line| /\A\S/ === line }.each {|e| pp e}
    }

    IO.popen([{"LC_ALL"=>"C"}, "svn", "proplist", "-R"]) {|f|
      f.lines.slice_before(/\AProp/).each {|lines| p lines }
    }

    a = [0,2,3,4,6,7,9]
    prev = a[0]
    p a.slice_before {|e|
      prev, prev2 = e, prev
      prev2 + 1 != e
    }.map {|es|
      es.length <= 2 ? es.join(",") : "#{es.first}-#{es.last}"
    }.join(",")

    # word wrapping.
    # this assumes all characters have same width.
    def wordwrap(words, maxwidth)
      # if cols is a local variable, 2nd "each" may start with non-zero cols.
      words.slice_before(cols: 0) {|w, h|
        h[:cols] += 1 if h[:cols] != 0
        h[:cols] += w.length
        if maxwidth < h[:cols]
          h[:cols] = w.length
          true
        else
          false
        end
      }
    end
    text = (1..20).to_a.join(" ")
    enum = wordwrap(text.split(/\s+/), 10)
    puts "-"*10
    enum.each {|ws| puts ws.join(" ") }
    puts "-"*10

    # parse mbox
    open("mbox") {|f|
      f.slice_before {|line|
        line.start_with? "From "
      }.each {|mail|
        unix_from = mail.shift
        i = mail.index("\n")
        header = mail[0...i]
        body = mail[(i+1)..-1]
        body.pop if body.last == "\n"
        fields = header.slice_before {|line| !" \t".include?(line[0]) }.to_a
        p unix_from
        pp fields
        pp body
      }
    }

    open("mbox") {|f|
      f.slice_before(emp: true) {|line,h|
        prevemp = h[:emp]
        h[:emp] = line == "\n"
        prevemp && line.start_with?("From ")
      }.each {|mail|
        mail.pop if mail.last == "\n"
        pp mail
      }
    }
#--------------------------------------------------
    %w(rhea kea flea).sort         #=> ["flea", "kea", "rhea"]
    (1..10).sort {|a,b| b <=> a}   #=> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
#-------------------------------------------------------------------------
    %w{ apple pear fig }.sort_by {|word| word.length}  #=> ["fig", "pear", "apple"]
 
    sorted = Dir["*"].sort_by {|f| test("M", f)}
    sorted   #=> ["OnLineBooks", "public_html", "ENV", "Notebooks", ...]
#---------------------------------------------------------------------------
    [1, 2, 3, 4, 5, 0].take(3)             #=> [1, 2, 3]
#-------------------------------------------------------------
    [1, 2, 3, 4, 5, 0].take_while {|i| i < 3 }   #=> [1, 2]
#-------------------------------------------------------------
    (1..7).to_a                       #=> [1, 2, 3, 4, 5, 6, 7]
    { 'a'=>1, 'b'=>2, 'c'=>3 }.to_a   #=> [["a", 1], ["b", 2], ["c", 3]]
#--------------------------------------------------------------------------
    a = [ 4, 5, 6 ]
    b = [ 7, 8, 9 ]

    [1,2,3].zip(a, b)      #=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
    [1,2].zip(a,b)         #=> [[1, 4, 7], [2, 5, 8]]
    a.zip([1,2],[8])       #=> [[4, 1, 8], [5, 2, nil], [6, nil, nil]]
#--------------------------------------------------------------------------
Clone this wiki locally