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

5.8. Iterowanie po elementach hasza w kolejności ich wstawiania

Problem

Iterowanie po haszu udostępnia jego elementy w kolejności losowej, a ich sortowanie — za pomocą pośredniczącej tablicy — możliwe jest tylko wtedy, jeśli ich klucze lub wartości są wzajemnie porównywalne. Jeśli nie są, jedyną „wyróżnioną” kolejnością elementów może być kolejność, w jakiej zostały one wstawione do hasza.

Rozwiązanie

Klasa OrderedHash, zdefiniowana w bibliotece orderedhash, funkcjonuje jak normalny hasz, jednocześnie definiując kolejność swych elementów jako kolejność ich wstawienia.

require 'orderedhash' h = OrderedHash.new h[1] = 1 h["Druga"] = 2 h[:Trzecia] = 3 h.keys # => [1, "Druga", :Trzecia] h.values # => [1, 2, 3] h.each { |k,v| puts "#{k} ...
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