All-About-Ruby-Arrays

Yes, ruby arrays. My little documentation on Arrays, reminders to myself on what’s really important. Showing how it works by example rather than just documentation. It’s like documentation that actually helps me.

[].join

Joins elements together with whatever you want…Let’s make a derp_fuck out of derp and fuck! [“derp”,“fuck”].join(’’) => “derpfuck”

This can be useful, if you have lots of elements and you want to combine then into a string

[].sort

I prefer sort_by (below). See http://brandon.dimcheff.com/2009/11/18/rubys-sort-vs-sort-by.html for more info on the differences

but if you just need a simple sort, .sort can be your best friend.

[2,3,1].sort
=> [1,2,3]

[].sort_by

[2, 3, 1].sort_by do |el|
  el
end
=> [1,2,3]

This will sort an array by the value returned in the block. Can be combined with hashes to make something very powerful.

my_pets = {
  "pets" => [
    {
      "name" => "Penny",
      "age" => 6
    }, {
      "name" => "Biscuit",
      "age" => 3
    }
  ]}


my_pets["pets"].sort_by do |pet|
  pet["age"]
end
=>  [{"name"=>"Biscuit", "age"=>3}, {"name"=>"Penny", "age"=>6}]

Want the reverse? mypets[“pets”].sortby do |pet| pet[“age”] end.reverse

=> [{"name"=>"Penny", "age"=>6}, ...]

Pretty magical.

Post Content