Skip to main content
1 of 4

Ruby: simplify the method to fetch keys based on an input value

I have a method to fetch keys based on a value passed in as an argument

def fetch_type_values(option)
 OPTIONS.map { |key, value| key if value.include?(option.to_s) }.compact.map(&:to_s)
end

OPTIONS are as:

    OPTIONS = {
      paper: %w[A4_paper countable universal],
      pencil: %w[trackable universal trackable],
      chalk: %w[stationery countable trackable A4_paper],
    }.freeze

when we pass an option to the method i.e. 'countable' it should return ["paper", "chalk"], which it does, and it's working how it's supposed to.

I just feel the method is a bit difficult to read, any way I can refactor/simplify it to make it more readable?