shorter way to do: `(cols[arr[0].to_sym].to_s + cols[arr[1].to_sym].to_s).to_i` ? in ruby

In Ruby, you can use the map method with a block to shorten the code and eliminate the need to convert the columns to strings and then to integers. Here's a shorter way to achieve the same result:

main.rb
arr.map { |x| cols[x.to_sym] }.reduce(:+)
42 chars
2 lines

Let's break down the code:

  1. The map method takes each element x in the arr array and replaces it with the corresponding value from cols[x.to_sym].
  2. The resulting array contains the values from cols for each key in arr.
  3. Finally, the reduce method with :+ as an argument sums up all the elements in the resulting array.

By using the map and reduce methods, you can achieve the same result in a shorter and more concise way.

related categories

gistlibby LogSnag