Ruby Tips 12 - Simplify your code with Ruby Array values_at

A programming language like Ruby comes with lots of features and capabilities which we often don’t learn in detail and instead end up rewriting things in our application code. This post shows how values_at in the Ruby Array class can simplify your code in some cases.

When converting files, I often end up with code that looks like this to read data from an input file and write a few of the columns to a different file.

1
2
3
4
5
6
7
8
g = File.open(ofile, 'w')
CSV.foreach(in_file) do |row|
  element = row[6]
  year = row[0]
  age = row[7]
  g.puts [element, year, age].join('|')
end
g.close

You can simplify this by doing this instead. Neat!

1
2
3
4
5
g = File.open(ofile, 'w')
CSV.foreach(in_file) do |row|
  g.puts row.values_at(6, 0, 7).join('|')
end
g.close

In this, values_at returns an array comprising the values for each of the index positions that was provided. The code looks really clean and simple and I think it conveys what the change well.

Here’s a look at what a simplified run looks like in irb:

irb(main):001> arr = [1, 3, 4, 5, 6, 7, 34, 46, 57, 34]
=> [1, 3, 4, 5, 6, 7, 34, 46, 57, 34]
irb(main):002> arr.values_at(0, 5, -1)
=> [1, 7, 34]

Additional Reading

Read the docs! The Ruby hash documentation is at: https://docs.ruby-lang.org/en/3.3/Array.html#method-i-values_at

In all honesty, I wrote this because I forget these things – and often end up rewriting it in application code myself. Hope you found it useful.

comments powered by Disqus