简体   繁体   中英

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?

如@mr_sudaca的评论所建议,解决方案是在数组上进行选择:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM