Reputation: 2734
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?
Upvotes: 0
Views: 129
Reputation: 2734
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) }]
Upvotes: 0