Last active
August 29, 2015 14:15
-
-
Save monkbroc/4edf88de9c8b26bbe013 to your computer and use it in GitHub Desktop.
Chunk example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Book = Struct.new(:title, :year_published) do | |
| def decade_published | |
| year_published - year_published % 10 | |
| end | |
| def to_s | |
| "#{title} (#{year_published})" | |
| end | |
| end | |
| bookshelf = [ | |
| Book.new("The Great Gatsby", 1925), | |
| Book.new("Gone with the Wind", 1936), | |
| Book.new("The Hobbit", 1937), | |
| Book.new("The Little Prince", 1940), | |
| Book.new("1984", 1949), | |
| Book.new("The Catcher in the Rye", 1951), | |
| Book.new("To Kill a Mockingbird", 1960), | |
| ] | |
| books_by_decade = bookshelf.chunk { |book| "#{book.decade_published}'s" } | |
| puts books_by_decade.to_a | |
| # 1920's | |
| # The Great Gatsby (1925) | |
| # 1930's | |
| # Gone with the Wind (1936) | |
| # The Hobbit (1937) | |
| # 1940's | |
| # The Little Prince (1940) | |
| # 1984 (1949) | |
| # 1950's | |
| # The Catcher in the Rye (1951) | |
| # 1960's | |
| # To Kill a Mockingbird (1960) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment