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.rb42 chars2 lines
Let's break down the code:
map
method takes each element x
in the arr
array and replaces it with the corresponding value from cols[x.to_sym]
.cols
for each key in arr
.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.
gistlibby LogSnag