Reason #80 •
March 21st, 2026
Hash #keys and #values
It's late Saturday night. Let's keep it simple but classy with the Hash keys and values methods. These methods allow us to extract the keys or values from a hash as arrays, which can be quite handy for various operations:
Ruby
page_views = {
landing_page: 108,
about_page: 1337,
pricing_page: 170,
}
dive_deeper_urls = page_views.keys.map do |page|
"https://analytics.example.com/#{page}"
end
# => [
# "https://analytics.example.com/landing_page",
# "https://analytics.example.com/about_page",
# "https://analytics.example.com/pricing_page",
# ]
total_page_views = page_views.values.sum
# => 1615
JavaScript
const pageViews = {
landingPage: 108,
aboutPage: 1337,
pricingPage: 170,
};
const diveDeeperUrls = Object.keys(pageViews).map(page =>
`https://analytics.example.com/${page}`
);
// => [
// "https://analytics.example.com/landingPage",
// "https://analytics.example.com/aboutPage",
// "https://analytics.example.com/pricingPage",
// ]
const totalPageViews = Object.values(pageViews)
.reduce((sum, views) => sum + views, 0);
// => 1615
These methods are good examples of how flexible Ruby's Hashes are for day-to-day programming!
JavaScript has been catching up here with Object.keys and the more recently introduced Object.values function, though it feels kind of weird that they aren't just functions on the objects themselves 🤷♂️
History
Both Hash#keys and Hash#values have been available in Ruby since its inception in 1995.
In JavaScript, Object.keys was introduced in ECMAScript 5 in 2009, while Object.values came much later in ECMAScript 2017.