Skip to Main Content
Ruby. Receptury
book

Ruby. Receptury

by Lucas Carlson, Leonard Richardson
November 2012
Intermediate to advanced content levelIntermediate to advanced
888 pages
54h 46m
Polish
Helion
Content preview from Ruby. Receptury

7.7. Nietypowe metody klasyfikujące i kolekcjonujące

Problem

Podstawowe metody blokowe, oferowane przez standardową bibliotekę języka Ruby, okazują się w danym zastosowaniu niewystarczające. Chcielibyśmy zdefiniować własne metody klasyfikowania elementów stanowiących wynik enumeracji (jak Enumerable#detect czy Enumerable#find_all) i kolekcjonowania tych elementów (jak Enumerable#collect).

Rozwiązanie

Metodę dokonującą przeszukiwania lub klasyfikowania elementów będących wynikiem enumeracji najłatwiej jest zaimplementować za pomocą iteratora inject. W ten sposób łatwo można stworzyć własne wersje metod w rodzaju detect i find_all:

module Enumerable def find_no_more_than(limit) inject([]) do |a,e| a << e if yield e return a if a.size ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

ReasonML Quick Start Guide

ReasonML Quick Start Guide

Raphael Rafatpanah, Bruno Joseph D'mello
Microsoft Excel: Formeln & Funktionen - Das Maxibuch, 3., aktualisierte und erweiterte Auflage

Microsoft Excel: Formeln & Funktionen - Das Maxibuch, 3., aktualisierte und erweiterte Auflage

Egbert Jeschke, Eckehard Pfeifer, Helmut Reinke, Sara Unverhau, Bodo Fienitz
Mastering Ruby Closures

Mastering Ruby Closures

Benjamin Tan Wei Hao

Publisher Resources

ISBN: 9781457177453Errata Page