A few lesser-known but useful Ruby (on Rails) methods: Hash and Enumerable

After having talked about some lesser-known Ruby (on Rails) Array methods, in this article I will do the same for the classes Hash and Enumerable. The methods that are part of Ruby on Rails will be marked with “[Rails]”. Hash default Returns the default value of the hash. There is also a “setter version” of […]

After having talked about some lesser-known Ruby (on Rails) Array methods, in this article I will do the same for the classes Hash and Enumerable. The methods that are part of Ruby on Rails will be marked with “[Rails]”.

Hash

default

Returns the default value of the hash. There is also a “setter version” of this method that sets the default value of the existing hash.

meal = Hash.new('wine') # a hash with the default value 'wine'
meal[:drink] # returns 'wine'
meal.default # returns 'wine'
meal.default = 'champagne' # the default is now 'champagne'
Wine from Compagnie des vins surnaturels, Paris

values_at(keys)

Returns an array containing the values associated with the given keys.

{ dish_name: 'chia pudding', healthy: true, cooking_skill_level: 1 }.values_at(:dish_name, :healthy)
# returns ['chia pudding', true]
Chia pudding, an excellent option for a healthy breakfast or snack. Image from minimalistbaker.com.

except(keys)

[Rails] Returns a hash that includes everything but the given keys.

{ name: 'truffle pasta', price: 50, cuisine: 'italian' }.except(:price) 
# returns { name: 'truffle pasta, cuisine: 'italian' }

extract!(keys)

[Rails] Returns the key/value pairs matching the given keys, removing them from the hash.

{ name: 'truffle pasta', price: 50, cuisine: 'italian' }.extract!(:name, :cuisine) 
# returns { name: 'truffle pasta, cuisine: 'italian' }

transform_keys/values

[Rails] Transforms keys or values using the provided block.

{ calories: 150, amount: 2 }.transform_values(&:to_s) 
# returns { calories: '150', amount: '2' }

deep_merge(other_hash)

[Rails] Recursively merges self and other_hash.

salad_1 = { vegetables: { greens: 'kale', root: 'carrot' }, protein: 'beef' }
salad_2 = { vegetables: { grilled: 'red pepper' }, protein: 'tofu' }
salad_1.deep_merge(salad_2)
# returns { vegetables: { greens: 'kale', root: 'carrot', grilled: 'red pepper' }, protein: 'tofu' } and makes this salad vegan
The salad from the example, recipe at https://minimalistbaker.com/crunchy-thai-kale-salad/.

Enumerable

reverse_each

Iterates over array elements in reverse order.

seeds = %w(chia flax pumpkin)
seeds.reverse_each { |s| print s, ' ' } 
# will print 'pumpkin flax chia'

group_by

Groups the elements of the enumerable based on the evaluation of the block.

food = [{ name: 'hamburger', healthy: false }, { name: 'Coca Cola', healthy: false }, { name: 'avocado toast', healthy: true }]
food.group_by { |f| f[:healthy] } 
# helps you make good choices and returns {false=>[{:name=>"hamburger", :healthy=>false}, {:name=>"Coca Cola", :healthy=>false}], true=>[{:name=>"avocado toast", :healthy=>true}]}

many?

[Rails] Returns true if the enumerable has more than 1 element.

%w(macaron croissant canelé).many? # returns true
I admit I’d eat *many* of these. Photo by Ladurée

pluck(keys)

[Rails] Similar to the ActiveRecord’s method of the same name. It extracts the values from the enumerable correspoinding to the specified keys.

[{ name: 'croissant', price: 1.5 }, { name: 'baguette', price: 1 }].pluck(:name) 
# returns ['croissant', 'baguette']

It’s just a few of the peculiar methods I discovered while browsing through Ruby and Rails documentation. Here you can find more:

And don’t hesitate to share if you spot something worthwhile!


A few lesser-known but useful Ruby (on Rails) methods: Hash and Enumerable was originally published in JobTeaser Tech on Medium, where people are continuing the conversation by highlighting and responding to this story.

Source: JobTeaser