scim scim - 2 months ago 4
Ruby Question

How can I translate an array using a hash?

What I'm trying to do is giving a list of columns, get an array of column formats. I have an array of column names, and a has where the key is the column name and the value is the format the column needs. If there's no value in the hash for a given column, it needs to be nil in the resulting array.


report_columns = ["val1", "val2", "subtotal",
"othertotal", "grand_total", "moar_total"]
column_formats = {"grand_total" => @highlight_money,
"subtotal" => @money}

I can easily do it with this code:

datatype_array = []
report_columns.each {|col| datatype_array << column_formats[col] }
# do stuff with datatype_array

But this is ruby. There's a more concise way to do this! Please let me know what magic method I'm missing.


You're first attempt should be a simple map rather than an each that accumulates onto an array.

datatype_array = { |c| column_formats[c] }

You can also splat the array of columns into Hash#values_at, which expects multiple key names as individual arguments:

datatype_array = column_formats.values_at(*report_columns)