Efficient Data Extraction With values_at In Ruby

Suman Awal March 26, 2024

In Ruby, values_at method can be used to retrieve specific elements from an array or hash. It returns an array with the values based on the parameters.

values_at with array (Ruby Official Doc)

ruby


array = ['ruby', 'c#', 'php', '.net', 'java']  
result_array = array.values_at(0,2) # This should returns an array with elements in index 0 and 2  
puts result_array # Output: ['ruby', 'php']

values_at with Hash (Ruby Official Doc)

ruby


hash_data = { name: 'Jack', role: 'software developer', company: 'Google', salary: '9000000'}  
# Let's assume we only want name and company values from the hash  
result_data = hash_data.values_at(:name, :company) # This should returns array with the value of provided key  
puts result_data # Output: ['Jack', 'Google']

As explained above, values_at method provided by Ruby is very useful for data extraction based on the use case. I personally preferred this method while extracting the required data from the third-party data source and creating CSV based on the data.