shorter way to do: ` cols = {black:0, brown:1, red:2} def value(arr) = (cols[arr[0].to_sym].to_s + cols[arr[1].to_sym].to_s).to_i end` ? in ruby

One way to make your code shorter is to use the fetch method of the Hash class instead of accessing the values using the square bracket syntax. Here's a shorter version of your code:

main.rb
cols = { black: 0, brown: 1, red: 2 }
def value(arr)
  (cols.fetch(arr[0].to_sym, "invalid input").to_s + cols.fetch(arr[1].to_sym, "invalid input").to_s).to_i
end
164 chars
5 lines

In this version, the fetch method is used to access the values from the cols hash. It takes the symbolized keys as arguments and returns the corresponding values. If the key is not found in the hash, it will return the specified default value.

Note that I've added a "invalid input" default value in case the key is not found in the cols hash. You can replace it with an actual error handling logic depending on your requirements.

related categories

gistlibby LogSnag