SlideShare une entreprise Scribd logo
1  sur  32
Gr             ou
 pi             ng
Ruby Method of the Month
Kevin Munc - @muncman
in_groups

in_groups_of
r
                    o s t
                  p n
                p o
          e e u si
             S n
      t
    c Exiv t
 A e                 y
                   a g
        r
      o :Ar i    r n
 : :C      :         p
               r o u
          : :G
http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Array/Grouping.html
Arrays into Groups
Follow Along in IRB!


• You’re going to need to use ActiveSupport:

  •require ‘active_support’
    • Note: require ‘activesupport’ (no underscore) is deprecated
       for removal in Rails 3.
A Colorful Array

seq = %w{turquoise ultramarine chartreuse
lavender crimson burgundy coral teal magenta
maroon cerulean fuchsia emerald taupe auburn
vermillion}

seq.size
=> 16
in_groups
seq.in_groups(4)
=>
[
["turquoise", "ultramarine", "chartreuse",
"lavender"],
["crimson", "burgundy", "coral", "teal"],
["magenta", "maroon", "cerulean", "fuchsia"],
["emerald", "taupe", "auburn", "vermillion"]
]
in_groups_of
seq.in_groups_of(4)
=>
[
["turquoise", "ultramarine", "chartreuse",
"lavender"],
["crimson", "burgundy", "coral", "teal"],
["magenta", "maroon", "cerulean", "fuchsia"],
["emerald", "taupe", "auburn", "vermillion"]
]
in_groups
seq.in_groups(3)
=>
[
["turquoise", "ultramarine", "chartreuse",
"lavender", "crimson", "burgundy"],
["coral", "teal", "magenta", "maroon", "cerulean",
nil],
["fuchsia", "emerald", "taupe", "auburn",
"vermillion", nil]
]
in_groups_of
seq.in_groups_of(3)
=>
[
["turquoise", "ultramarine", "chartreuse"],
["lavender", "crimson", "burgundy"],
["coral", "teal", "magenta"],
["maroon", "cerulean", "fuchsia"],
["emerald", "taupe", "auburn"],
["vermillion", nil, nil]
]
in_groups with false
seq.in_groups(3, false)
=>
[
["turquoise", "ultramarine", "chartreuse",
"lavender", "crimson", "burgundy"],
["coral", "teal", "magenta", "maroon", "cerulean"],
["fuchsia", "emerald", "taupe", "auburn",
"vermillion"]
]
in_groups_of with false
seq.in_groups_of(3, false)
=>
[
["turquoise", "ultramarine", "chartreuse"],
["lavender", "crimson", "burgundy"],
["coral", "teal", "magenta"],
["maroon", "cerulean", "fuchsia"],
["emerald", "taupe", "auburn"],
["vermillion"]
]
in_groups with filler
seq.in_groups(3, 'white')
=>
[
["turquoise", "ultramarine", "chartreuse",
"lavender", "crimson", "burgundy"],
["coral", "teal", "magenta", "maroon", "cerulean",
"white"],
["fuchsia", "emerald", "taupe", "auburn",
"vermillion", "white"]
]
in_groups_of with filler
seq.in_groups_of(3, 'white')
=>
[
["turquoise", "ultramarine", "chartreuse"],
["lavender", "crimson", "burgundy"],
["coral", "teal", "magenta"],
["maroon", "cerulean", "fuchsia"],
["emerald", "taupe", "auburn"],
["vermillion", "white", "white"]
]
Warning:
The next two slides
       have
   Information
     Overload
Another Look:
                      in_groups
gen = []; 20.times { |i| gen << i+1 }; gen
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]


gen.in_groups(4) # into four groups
=> [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]

gen.in_groups(3) # into three groups
=> [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, nil]]

gen.in_groups(3, false) # into three groups, unpadded
=> [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20]]

gen.in_groups(3, 99) # into three groups, with filler
=> [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 99]]
Another Look:
                     in_groups_of
gen = []; 20.times { |i| gen << i+1 }; gen
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]


gen.in_groups_of(4) # into groups of four
=> [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]]

gen.in_groups_of(3) # into groups of three
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, nil]]

gen.in_groups_of(3, false) # into groups of three, unpadded
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20]]

gen.in_groups_of(3, 99) # into groups of three, with filler
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 99]]
Bonus Method!
split

• Divide an array based on:
  • delimiter
  • or block
  • but not both
    • a block is used if present
• This is the third and final method in
  ActiveSupport::CoreExtensions::Array::
  Grouping
split it. split it good!

a_ray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a_ray.split(5)
=> [[1, 2, 3, 4], [6, 7, 8, 9, 10]]
split it. split it good!

a_ray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a_ray.split(5)
=> [[1, 2, 3, 4], [6, 7, 8, 9, 10]]

b_ray = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
b_ray.split(3)
=> [[1, 2], [4, 5, 1, 2], [4, 5]]
split it like it’s hot
a_ray
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a_ray.split { |elem| elem % 2 == 0 }
=> [[1], [3], [5], [7], [9], []]
split it like it’s hot
a_ray
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a_ray.split { |elem| elem % 2 == 0 }
=> [[1], [3], [5], [7], [9], []]

a_ray
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a_ray.split { |elem| elem % 2 == 1 }
=> [[], [2], [4], [6], [8], [10]]
splitting hairs
b_ray
=> [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

b_ray.split do |elem|
 (3..5).include? elem
end

=> [[1, 2], [], [], [1, 2], [], [], []]

      # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90
  90:         def split(value = nil)
  91:           using_block = block_given?
  92:
  93:           inject([[]]) do |results, element|
  94:             if (using_block && yield(element)) || (value == element)
  95:               results << []
  96:             else
  97:               results.last << element
  98:             end
  99:
 100:             results
splitting hairs
b_ray
=> [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]                                                  Matches are
                                                                                excluded, starting a
                                                                                 new array group.
b_ray.split do |elem|
 (3..5).include? elem
end

=> [[1, 2], [], [], [1, 2], [], [], []]

      # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90
  90:         def split(value = nil)
  91:           using_block = block_given?
  92:
  93:           inject([[]]) do |results, element|
  94:             if (using_block && yield(element)) || (value == element)
  95:               results << []
  96:             else
  97:               results.last << element
  98:             end
  99:
 100:             results
splitting hairs
b_ray
=> [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]                                                  Matches are
                                                                                excluded, starting a
                                                                                 new array group.
b_ray.split do |elem|
 (3..5).include? elem
end

=> [[1, 2], [], [], [1, 2], [], [], []]
            3
      # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90
  90:         def split(value = nil)
  91:           using_block = block_given?
  92:
  93:           inject([[]]) do |results, element|
  94:             if (using_block && yield(element)) || (value == element)
  95:               results << []
  96:             else
  97:               results.last << element
  98:             end
  99:
 100:             results
splitting hairs
b_ray
=> [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]                                                  Matches are
                                                                                excluded, starting a
                                                                                 new array group.
b_ray.split do |elem|
 (3..5).include? elem
end

=> [[1, 2], [], [], [1, 2], [], [], []]
            3 4
      # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90
  90:         def split(value = nil)
  91:           using_block = block_given?
  92:
  93:           inject([[]]) do |results, element|
  94:             if (using_block && yield(element)) || (value == element)
  95:               results << []
  96:             else
  97:               results.last << element
  98:             end
  99:
 100:             results
splitting hairs
b_ray
=> [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]                                                  Matches are
                                                                                excluded, starting a
                                                                                 new array group.
b_ray.split do |elem|
 (3..5).include? elem
end

=> [[1, 2], [], [], [1, 2], [], [], []]
            3 4 5
      # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90
  90:         def split(value = nil)
  91:           using_block = block_given?
  92:
  93:           inject([[]]) do |results, element|
  94:             if (using_block && yield(element)) || (value == element)
  95:               results << []
  96:             else
  97:               results.last << element
  98:             end
  99:
 100:             results
splitting hairs
b_ray
=> [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]                                                  Matches are
                                                                                excluded, starting a
                                                                                 new array group.
b_ray.split do |elem|
 (3..5).include? elem
end

=> [[1, 2], [], [], [1, 2], [], [], []]
            3 4 5           3
      # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90
  90:         def split(value = nil)
  91:           using_block = block_given?
  92:
  93:           inject([[]]) do |results, element|
  94:             if (using_block && yield(element)) || (value == element)
  95:               results << []
  96:             else
  97:               results.last << element
  98:             end
  99:
 100:             results
splitting hairs
b_ray
=> [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]                                                  Matches are
                                                                                excluded, starting a
                                                                                 new array group.
b_ray.split do |elem|
 (3..5).include? elem
end

=> [[1, 2], [], [], [1, 2], [], [], []]
            3 4 5           3 4
      # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90
  90:         def split(value = nil)
  91:           using_block = block_given?
  92:
  93:           inject([[]]) do |results, element|
  94:             if (using_block && yield(element)) || (value == element)
  95:               results << []
  96:             else
  97:               results.last << element
  98:             end
  99:
 100:             results
splitting hairs
b_ray
=> [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]                                                  Matches are
                                                                                excluded, starting a
                                                                                 new array group.
b_ray.split do |elem|
 (3..5).include? elem
end

=> [[1, 2], [], [], [1, 2], [], [], []]
            3 4 5           3 4 5
      # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90
  90:         def split(value = nil)
  91:           using_block = block_given?
  92:
  93:           inject([[]]) do |results, element|
  94:             if (using_block && yield(element)) || (value == element)
  95:               results << []
  96:             else
  97:               results.last << element
  98:             end
  99:
 100:             results
Questions?


               Image Credits
        all from clickykbd@flickr
http://www.flickr.com/photos/clickykbd

Contenu connexe

Tendances

An Introduction to Data Mining with R
An Introduction to Data Mining with RAn Introduction to Data Mining with R
An Introduction to Data Mining with RYanchang Zhao
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesPython PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesIHTMINSTITUTE
 
Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)Mohd Tousif
 

Tendances (7)

An Introduction to Data Mining with R
An Introduction to Data Mining with RAn Introduction to Data Mining with R
An Introduction to Data Mining with R
 
Python idioms
Python idiomsPython idioms
Python idioms
 
Session 02
Session 02Session 02
Session 02
 
Aimsstrand1po6gr3expandednotation
Aimsstrand1po6gr3expandednotationAimsstrand1po6gr3expandednotation
Aimsstrand1po6gr3expandednotation
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesPython PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
 
Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)
 
Data types
Data typesData types
Data types
 

En vedette

Milieuproblematiek
MilieuproblematiekMilieuproblematiek
Milieuproblematiekguestc4804d
 
cycle (MOTM 2010.07)
cycle (MOTM 2010.07)cycle (MOTM 2010.07)
cycle (MOTM 2010.07)Kevin Munc
 
Percent Literals (MOTM 2010.09)
Percent Literals (MOTM 2010.09)Percent Literals (MOTM 2010.09)
Percent Literals (MOTM 2010.09)Kevin Munc
 
Lookin Out - Program Overview
Lookin Out - Program OverviewLookin Out - Program Overview
Lookin Out - Program Overviewmbresee
 
Apples & Oranges? Adventures in Equality Comparison & one of the ‘Bad Parts’
Apples & Oranges? Adventures in Equality Comparison & one of the ‘Bad Parts’Apples & Oranges? Adventures in Equality Comparison & one of the ‘Bad Parts’
Apples & Oranges? Adventures in Equality Comparison & one of the ‘Bad Parts’Kevin Munc
 
Lean manufacturing &amp; lean supply chain awareness workshop
Lean manufacturing &amp; lean supply chain awareness workshopLean manufacturing &amp; lean supply chain awareness workshop
Lean manufacturing &amp; lean supply chain awareness workshopAdvanced Value Group, LLC
 
Helpers (MOTM 2010.03)
Helpers (MOTM 2010.03)Helpers (MOTM 2010.03)
Helpers (MOTM 2010.03)Kevin Munc
 
NaN, Zero, & Infinities
NaN, Zero, & InfinitiesNaN, Zero, & Infinities
NaN, Zero, & InfinitiesKevin Munc
 
Ci for i-os-codemash-01.2013
Ci for i-os-codemash-01.2013Ci for i-os-codemash-01.2013
Ci for i-os-codemash-01.2013Kevin Munc
 

En vedette (10)

Milieuproblematiek
MilieuproblematiekMilieuproblematiek
Milieuproblematiek
 
cycle (MOTM 2010.07)
cycle (MOTM 2010.07)cycle (MOTM 2010.07)
cycle (MOTM 2010.07)
 
Percent Literals (MOTM 2010.09)
Percent Literals (MOTM 2010.09)Percent Literals (MOTM 2010.09)
Percent Literals (MOTM 2010.09)
 
Lookin Out - Program Overview
Lookin Out - Program OverviewLookin Out - Program Overview
Lookin Out - Program Overview
 
Shellwords
ShellwordsShellwords
Shellwords
 
Apples & Oranges? Adventures in Equality Comparison & one of the ‘Bad Parts’
Apples & Oranges? Adventures in Equality Comparison & one of the ‘Bad Parts’Apples & Oranges? Adventures in Equality Comparison & one of the ‘Bad Parts’
Apples & Oranges? Adventures in Equality Comparison & one of the ‘Bad Parts’
 
Lean manufacturing &amp; lean supply chain awareness workshop
Lean manufacturing &amp; lean supply chain awareness workshopLean manufacturing &amp; lean supply chain awareness workshop
Lean manufacturing &amp; lean supply chain awareness workshop
 
Helpers (MOTM 2010.03)
Helpers (MOTM 2010.03)Helpers (MOTM 2010.03)
Helpers (MOTM 2010.03)
 
NaN, Zero, & Infinities
NaN, Zero, & InfinitiesNaN, Zero, & Infinities
NaN, Zero, & Infinities
 
Ci for i-os-codemash-01.2013
Ci for i-os-codemash-01.2013Ci for i-os-codemash-01.2013
Ci for i-os-codemash-01.2013
 

Similaire à Grouping (MOTM 2010.02)

Ruby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examplesRuby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examplesNiranjan Sarade
 
Python PCEP Operations On Lists
Python PCEP Operations On ListsPython PCEP Operations On Lists
Python PCEP Operations On ListsIHTMINSTITUTE
 
K means cluster ML
K means cluster  MLK means cluster  ML
K means cluster MLBangalore
 
Clustering K means and Hierarchical - NLP
Clustering K means and Hierarchical - NLPClustering K means and Hierarchical - NLP
Clustering K means and Hierarchical - NLPRupak Roy
 
R is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdfR is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdfannikasarees
 
[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2Kevin Chun-Hsien Hsu
 
NumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxNumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxJohnWilliam111370
 
Useful javascript
Useful javascriptUseful javascript
Useful javascriptLei Kang
 
Activesupport - Leckerbissen (Kurzvortrag)
Activesupport - Leckerbissen (Kurzvortrag)Activesupport - Leckerbissen (Kurzvortrag)
Activesupport - Leckerbissen (Kurzvortrag)Robert Gogolok
 
Unit 4 lesson 5 distributive property
Unit 4 lesson 5 distributive propertyUnit 4 lesson 5 distributive property
Unit 4 lesson 5 distributive propertymlabuski
 
Unit 4 lesson 5 distributive property
Unit 4 lesson 5 distributive propertyUnit 4 lesson 5 distributive property
Unit 4 lesson 5 distributive propertymlabuski
 
Python Usage (5-minute-summary)
Python Usage (5-minute-summary)Python Usage (5-minute-summary)
Python Usage (5-minute-summary)Ohgyun Ahn
 
Day 1c access, select ordering copy.pptx
Day 1c   access, select   ordering copy.pptxDay 1c   access, select   ordering copy.pptx
Day 1c access, select ordering copy.pptxAdrien Melquiond
 
019# mean, median, mode
019# mean, median, mode019# mean, median, mode
019# mean, median, modeAbdul ghafoor
 
Inside Enumerable
Inside EnumerableInside Enumerable
Inside EnumerableMike Bowler
 
Ruby初級者向けレッスン 48回 ─── Array と Hash
Ruby初級者向けレッスン 48回 ─── Array と HashRuby初級者向けレッスン 48回 ─── Array と Hash
Ruby初級者向けレッスン 48回 ─── Array と Hashhigaki
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in rubyKoen Handekyn
 
Poodr ch8-composition
Poodr ch8-compositionPoodr ch8-composition
Poodr ch8-compositionorga shih
 

Similaire à Grouping (MOTM 2010.02) (20)

Ruby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examplesRuby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examples
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 
Python PCEP Operations On Lists
Python PCEP Operations On ListsPython PCEP Operations On Lists
Python PCEP Operations On Lists
 
K means cluster ML
K means cluster  MLK means cluster  ML
K means cluster ML
 
Clustering K means and Hierarchical - NLP
Clustering K means and Hierarchical - NLPClustering K means and Hierarchical - NLP
Clustering K means and Hierarchical - NLP
 
R is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdfR is a very flexible and powerful programming language, as well as a.pdf
R is a very flexible and powerful programming language, as well as a.pdf
 
[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2[1062BPY12001] Data analysis with R / week 2
[1062BPY12001] Data analysis with R / week 2
 
Lec13 Clustering.pptx
Lec13 Clustering.pptxLec13 Clustering.pptx
Lec13 Clustering.pptx
 
NumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxNumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptx
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
Activesupport - Leckerbissen (Kurzvortrag)
Activesupport - Leckerbissen (Kurzvortrag)Activesupport - Leckerbissen (Kurzvortrag)
Activesupport - Leckerbissen (Kurzvortrag)
 
Unit 4 lesson 5 distributive property
Unit 4 lesson 5 distributive propertyUnit 4 lesson 5 distributive property
Unit 4 lesson 5 distributive property
 
Unit 4 lesson 5 distributive property
Unit 4 lesson 5 distributive propertyUnit 4 lesson 5 distributive property
Unit 4 lesson 5 distributive property
 
Python Usage (5-minute-summary)
Python Usage (5-minute-summary)Python Usage (5-minute-summary)
Python Usage (5-minute-summary)
 
Day 1c access, select ordering copy.pptx
Day 1c   access, select   ordering copy.pptxDay 1c   access, select   ordering copy.pptx
Day 1c access, select ordering copy.pptx
 
019# mean, median, mode
019# mean, median, mode019# mean, median, mode
019# mean, median, mode
 
Inside Enumerable
Inside EnumerableInside Enumerable
Inside Enumerable
 
Ruby初級者向けレッスン 48回 ─── Array と Hash
Ruby初級者向けレッスン 48回 ─── Array と HashRuby初級者向けレッスン 48回 ─── Array と Hash
Ruby初級者向けレッスン 48回 ─── Array と Hash
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
 
Poodr ch8-composition
Poodr ch8-compositionPoodr ch8-composition
Poodr ch8-composition
 

Plus de Kevin Munc

Basic Scheduling with setTimeout & setInterval
Basic Scheduling with setTimeout & setIntervalBasic Scheduling with setTimeout & setInterval
Basic Scheduling with setTimeout & setIntervalKevin Munc
 
Number Conversions (MOTM 2010.12)
Number Conversions (MOTM 2010.12)Number Conversions (MOTM 2010.12)
Number Conversions (MOTM 2010.12)Kevin Munc
 
empty?, nil?, blank?, & present? (MOTM 2010.05)
empty?, nil?, blank?, & present? (MOTM 2010.05)empty?, nil?, blank?, & present? (MOTM 2010.05)
empty?, nil?, blank?, & present? (MOTM 2010.05)Kevin Munc
 
Take & Drop (MOTM 2010.04)
Take & Drop (MOTM 2010.04)Take & Drop (MOTM 2010.04)
Take & Drop (MOTM 2010.04)Kevin Munc
 
Removing Methods (MOTM 2010.01)
Removing Methods (MOTM 2010.01)Removing Methods (MOTM 2010.01)
Removing Methods (MOTM 2010.01)Kevin Munc
 
gsub (MOTM 2009.09)
gsub (MOTM 2009.09)gsub (MOTM 2009.09)
gsub (MOTM 2009.09)Kevin Munc
 
The Methods Method and Its Friends (MOTM 2009.08)
The Methods Method and Its Friends (MOTM 2009.08)The Methods Method and Its Friends (MOTM 2009.08)
The Methods Method and Its Friends (MOTM 2009.08)Kevin Munc
 
Ruby's String Slicing (MOTM 2009.07)
Ruby's String Slicing (MOTM 2009.07)Ruby's String Slicing (MOTM 2009.07)
Ruby's String Slicing (MOTM 2009.07)Kevin Munc
 

Plus de Kevin Munc (8)

Basic Scheduling with setTimeout & setInterval
Basic Scheduling with setTimeout & setIntervalBasic Scheduling with setTimeout & setInterval
Basic Scheduling with setTimeout & setInterval
 
Number Conversions (MOTM 2010.12)
Number Conversions (MOTM 2010.12)Number Conversions (MOTM 2010.12)
Number Conversions (MOTM 2010.12)
 
empty?, nil?, blank?, & present? (MOTM 2010.05)
empty?, nil?, blank?, & present? (MOTM 2010.05)empty?, nil?, blank?, & present? (MOTM 2010.05)
empty?, nil?, blank?, & present? (MOTM 2010.05)
 
Take & Drop (MOTM 2010.04)
Take & Drop (MOTM 2010.04)Take & Drop (MOTM 2010.04)
Take & Drop (MOTM 2010.04)
 
Removing Methods (MOTM 2010.01)
Removing Methods (MOTM 2010.01)Removing Methods (MOTM 2010.01)
Removing Methods (MOTM 2010.01)
 
gsub (MOTM 2009.09)
gsub (MOTM 2009.09)gsub (MOTM 2009.09)
gsub (MOTM 2009.09)
 
The Methods Method and Its Friends (MOTM 2009.08)
The Methods Method and Its Friends (MOTM 2009.08)The Methods Method and Its Friends (MOTM 2009.08)
The Methods Method and Its Friends (MOTM 2009.08)
 
Ruby's String Slicing (MOTM 2009.07)
Ruby's String Slicing (MOTM 2009.07)Ruby's String Slicing (MOTM 2009.07)
Ruby's String Slicing (MOTM 2009.07)
 

Dernier

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 

Dernier (20)

MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

Grouping (MOTM 2010.02)

  • 1. Gr ou pi ng Ruby Method of the Month Kevin Munc - @muncman
  • 3. r o s t p n p o e e u si S n t c Exiv t A e y a g r o :Ar i r n : :C : p r o u : :G http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/Array/Grouping.html
  • 5. Follow Along in IRB! • You’re going to need to use ActiveSupport: •require ‘active_support’ • Note: require ‘activesupport’ (no underscore) is deprecated for removal in Rails 3.
  • 6. A Colorful Array seq = %w{turquoise ultramarine chartreuse lavender crimson burgundy coral teal magenta maroon cerulean fuchsia emerald taupe auburn vermillion} seq.size => 16
  • 7. in_groups seq.in_groups(4) => [ ["turquoise", "ultramarine", "chartreuse", "lavender"], ["crimson", "burgundy", "coral", "teal"], ["magenta", "maroon", "cerulean", "fuchsia"], ["emerald", "taupe", "auburn", "vermillion"] ]
  • 8. in_groups_of seq.in_groups_of(4) => [ ["turquoise", "ultramarine", "chartreuse", "lavender"], ["crimson", "burgundy", "coral", "teal"], ["magenta", "maroon", "cerulean", "fuchsia"], ["emerald", "taupe", "auburn", "vermillion"] ]
  • 9. in_groups seq.in_groups(3) => [ ["turquoise", "ultramarine", "chartreuse", "lavender", "crimson", "burgundy"], ["coral", "teal", "magenta", "maroon", "cerulean", nil], ["fuchsia", "emerald", "taupe", "auburn", "vermillion", nil] ]
  • 10. in_groups_of seq.in_groups_of(3) => [ ["turquoise", "ultramarine", "chartreuse"], ["lavender", "crimson", "burgundy"], ["coral", "teal", "magenta"], ["maroon", "cerulean", "fuchsia"], ["emerald", "taupe", "auburn"], ["vermillion", nil, nil] ]
  • 11. in_groups with false seq.in_groups(3, false) => [ ["turquoise", "ultramarine", "chartreuse", "lavender", "crimson", "burgundy"], ["coral", "teal", "magenta", "maroon", "cerulean"], ["fuchsia", "emerald", "taupe", "auburn", "vermillion"] ]
  • 12. in_groups_of with false seq.in_groups_of(3, false) => [ ["turquoise", "ultramarine", "chartreuse"], ["lavender", "crimson", "burgundy"], ["coral", "teal", "magenta"], ["maroon", "cerulean", "fuchsia"], ["emerald", "taupe", "auburn"], ["vermillion"] ]
  • 13. in_groups with filler seq.in_groups(3, 'white') => [ ["turquoise", "ultramarine", "chartreuse", "lavender", "crimson", "burgundy"], ["coral", "teal", "magenta", "maroon", "cerulean", "white"], ["fuchsia", "emerald", "taupe", "auburn", "vermillion", "white"] ]
  • 14. in_groups_of with filler seq.in_groups_of(3, 'white') => [ ["turquoise", "ultramarine", "chartreuse"], ["lavender", "crimson", "burgundy"], ["coral", "teal", "magenta"], ["maroon", "cerulean", "fuchsia"], ["emerald", "taupe", "auburn"], ["vermillion", "white", "white"] ]
  • 15. Warning: The next two slides have Information Overload
  • 16. Another Look: in_groups gen = []; 20.times { |i| gen << i+1 }; gen => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] gen.in_groups(4) # into four groups => [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]] gen.in_groups(3) # into three groups => [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, nil]] gen.in_groups(3, false) # into three groups, unpadded => [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20]] gen.in_groups(3, 99) # into three groups, with filler => [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 99]]
  • 17. Another Look: in_groups_of gen = []; 20.times { |i| gen << i+1 }; gen => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] gen.in_groups_of(4) # into groups of four => [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16], [17, 18, 19, 20]] gen.in_groups_of(3) # into groups of three => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, nil]] gen.in_groups_of(3, false) # into groups of three, unpadded => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20]] gen.in_groups_of(3, 99) # into groups of three, with filler => [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 99]]
  • 19. split • Divide an array based on: • delimiter • or block • but not both • a block is used if present • This is the third and final method in ActiveSupport::CoreExtensions::Array:: Grouping
  • 20. split it. split it good! a_ray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a_ray.split(5) => [[1, 2, 3, 4], [6, 7, 8, 9, 10]]
  • 21. split it. split it good! a_ray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a_ray.split(5) => [[1, 2, 3, 4], [6, 7, 8, 9, 10]] b_ray = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] b_ray.split(3) => [[1, 2], [4, 5, 1, 2], [4, 5]]
  • 22. split it like it’s hot a_ray => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a_ray.split { |elem| elem % 2 == 0 } => [[1], [3], [5], [7], [9], []]
  • 23. split it like it’s hot a_ray => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a_ray.split { |elem| elem % 2 == 0 } => [[1], [3], [5], [7], [9], []] a_ray => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a_ray.split { |elem| elem % 2 == 1 } => [[], [2], [4], [6], [8], [10]]
  • 24. splitting hairs b_ray => [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] b_ray.split do |elem| (3..5).include? elem end => [[1, 2], [], [], [1, 2], [], [], []] # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90 90: def split(value = nil) 91: using_block = block_given? 92: 93: inject([[]]) do |results, element| 94: if (using_block && yield(element)) || (value == element) 95: results << [] 96: else 97: results.last << element 98: end 99: 100: results
  • 25. splitting hairs b_ray => [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] Matches are excluded, starting a new array group. b_ray.split do |elem| (3..5).include? elem end => [[1, 2], [], [], [1, 2], [], [], []] # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90 90: def split(value = nil) 91: using_block = block_given? 92: 93: inject([[]]) do |results, element| 94: if (using_block && yield(element)) || (value == element) 95: results << [] 96: else 97: results.last << element 98: end 99: 100: results
  • 26. splitting hairs b_ray => [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] Matches are excluded, starting a new array group. b_ray.split do |elem| (3..5).include? elem end => [[1, 2], [], [], [1, 2], [], [], []] 3 # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90 90: def split(value = nil) 91: using_block = block_given? 92: 93: inject([[]]) do |results, element| 94: if (using_block && yield(element)) || (value == element) 95: results << [] 96: else 97: results.last << element 98: end 99: 100: results
  • 27. splitting hairs b_ray => [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] Matches are excluded, starting a new array group. b_ray.split do |elem| (3..5).include? elem end => [[1, 2], [], [], [1, 2], [], [], []] 3 4 # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90 90: def split(value = nil) 91: using_block = block_given? 92: 93: inject([[]]) do |results, element| 94: if (using_block && yield(element)) || (value == element) 95: results << [] 96: else 97: results.last << element 98: end 99: 100: results
  • 28. splitting hairs b_ray => [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] Matches are excluded, starting a new array group. b_ray.split do |elem| (3..5).include? elem end => [[1, 2], [], [], [1, 2], [], [], []] 3 4 5 # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90 90: def split(value = nil) 91: using_block = block_given? 92: 93: inject([[]]) do |results, element| 94: if (using_block && yield(element)) || (value == element) 95: results << [] 96: else 97: results.last << element 98: end 99: 100: results
  • 29. splitting hairs b_ray => [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] Matches are excluded, starting a new array group. b_ray.split do |elem| (3..5).include? elem end => [[1, 2], [], [], [1, 2], [], [], []] 3 4 5 3 # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90 90: def split(value = nil) 91: using_block = block_given? 92: 93: inject([[]]) do |results, element| 94: if (using_block && yield(element)) || (value == element) 95: results << [] 96: else 97: results.last << element 98: end 99: 100: results
  • 30. splitting hairs b_ray => [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] Matches are excluded, starting a new array group. b_ray.split do |elem| (3..5).include? elem end => [[1, 2], [], [], [1, 2], [], [], []] 3 4 5 3 4 # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90 90: def split(value = nil) 91: using_block = block_given? 92: 93: inject([[]]) do |results, element| 94: if (using_block && yield(element)) || (value == element) 95: results << [] 96: else 97: results.last << element 98: end 99: 100: results
  • 31. splitting hairs b_ray => [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] Matches are excluded, starting a new array group. b_ray.split do |elem| (3..5).include? elem end => [[1, 2], [], [], [1, 2], [], [], []] 3 4 5 3 4 5 # File activesupport/lib/active_support/core_ext/array/grouping.rb, line 90 90: def split(value = nil) 91: using_block = block_given? 92: 93: inject([[]]) do |results, element| 94: if (using_block && yield(element)) || (value == element) 95: results << [] 96: else 97: results.last << element 98: end 99: 100: results
  • 32. Questions? Image Credits all from clickykbd@flickr http://www.flickr.com/photos/clickykbd

Notes de l'éditeur