Thursday, September 8, 2016

Quick Tip: The Many Ways to Create a Hash in Ruby

As Rubyists, we use Hashes for everything. They are just so danged easy and useful. I mean, how often do you need something keyed to something else? A lot, if you're like me. For example, I have four (4) kids, which is a lot. I like to carry around a Hash like this one so I don't forget their names:

$> kids = {1: "Logan", 2: "Emma", 3: "Lily", 4: "Becca"}

Well, this is how I started, but that is little more than a glorified array. Plus, I found myself needing all kinds of information about them, so I changed the hash:

$> kids = {logan: { gender: :boy, dob: Date.new(2000, 12,24), sports: [:soccer], favorite: false } ... }

You get the idea. This Hash has served me well for quite some time, but I thought I'd look into some different ways to create this hash to see if I could make it even more useful.

This is Your Grandparents' Hash Creation

Continue reading %Quick Tip: The Many Ways to Create a Hash in Ruby%


by Glenn Goodrich via SitePoint

No comments:

Post a Comment