Skip to content

Commit af92a20

Browse files
sorting examples
1 parent b727869 commit af92a20

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

chapters/Hashes.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -449,6 +449,27 @@ FrozenError (can't modify frozen String)
449449
450450
## <a name="miscellaneous"></a>Miscellaneous
451451
452+
* use Enumerable methods `sort` and `sort_by` for sorting needs
453+
* the output is an array of arrays, so convert back to hash when needed
454+
455+
```ruby
456+
>> marks = {"foo" => 90, "baz" => 80, "lo" => 73, "kek" => 62}
457+
=> {"foo"=>90, "baz"=>80, "lo"=>73, "kek"=>62}
458+
459+
# by default, keys get sorted in ascending order
460+
>> marks.sort
461+
=> [["baz", 80], ["foo", 90], ["kek", 62], ["lo", 73]]
462+
# block form example
463+
>> marks.sort { |a, b| b[0] <=> a[0] }.to_h
464+
=> {"lo"=>73, "kek"=>62, "foo"=>90, "baz"=>80}
465+
>> marks.sort { |a, b| a[1] <=> b[1] }.to_h
466+
=> {"kek"=>62, "lo"=>73, "baz"=>80, "foo"=>90}
467+
468+
# sort_by example
469+
>> marks.sort_by { |k, v| -v }.to_h
470+
=> {"foo"=>90, "baz"=>80, "lo"=>73, "kek"=>62}
471+
```
472+
452473
* `flatten` method will convert hash to array with each key-value pair forming two elements
453474
* optional argument allows to specify depth of flattening
454475
* `compact` method will remove all keys with `nil` value

0 commit comments

Comments
 (0)