do enums work with indifferent access

 

Yes
Implements a hash where keys :foo and "foo" are considered to be the same.
enum provider_name: {
trade_me: ‘Trade Me’,
facebook: ‘Facebook’,
google: ‘Google’
}
irb(main):010:0> provider = ‘google’
=> “google”
irb(main):011:0> provider.to_s
=> “google”
irb(main):012:0> provider.to_sym
=> :google
irb(main):013:0> ThirdPartyIdentity.provider_names[provider.to_sym]
=> “Google”
irb(main):014:0> ThirdPartyIdentity.provider_names[provider.to_s]
=> “Google”
https://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html
rgb = ActiveSupport::HashWithIndifferentAccess.new

rgb[:black] = '#000000'
rgb[:black]  # => '#000000'
rgb['black'] # => '#000000'

rgb['white'] = '#FFFFFF'
rgb[:white]  # => '#FFFFFF'
rgb['white'] # => '#FFFFFF'

Internally symbols are mapped to strings when used as keys in the entire writing interface (calling []=merge, etc). This mapping belongs to the public interface. For example, given:

hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)

You are guaranteed that the key is returned as a string:

hash.keys # => ["a"]

Technically other types of keys are accepted:

hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
hash[0] = 0
hash # => {"a"=>1, 0=>0}

but this class is intended for use cases where strings or symbols are the expected keys and it is convenient to understand both as the same. For example the params hash in Ruby on Rails.

Note that core extensions define Hash#with_indifferent_access:

rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access

which may be handy.

To access this class outside of Rails, require the core extension with:

require "active_support/core_ext/hash/indifferent_access"

which will, in turn, require this file.

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注