Search code examples
rubysymbolsruby-1.8.7

Ruby 1.8.7 Array of symbols raising TypeError: Symbol as array index


I recently created a pull request for a gem which is building on travis against quite old ruby versions for backward compatibility.

In my commit I wanted to introduce a whitelist on some method options passed as an hash parameter.

In Rails with a recent ruby version it would look like:

MY_WHITELIST = %i(a b c)
def my_method(options={})
  @options = options.slice(*MY_WHITELIST)
end

In order to grant backward compatibility in a standalone gem, I provided a solution like:

MY_WHITELIST = [:a, :b, :c]
def my_method(options={})
  @options = options.select { |k, _| MY_WHITELIST.include?(k) }
end

This pass for ruby 1.9.3 but raise the following exception for 1.8.7:

TypeError: Symbol as array index

According to the documentation, this way to initialise an array should be accepted.

Have you ever experienced with use? What would you suggest?


Solution

  • As suggested in a comment by @mr_sudaca, the solution was to make the selection on an array:

    Hash[options.to_a.select { |k, _| MY_WHITELIST.include?(k) }]