Can you explain the difference between ActiveSupport’s HashWithIndifferentAccess and Ruby’s Hash ?
Can you explain the difference between ActiveSupport’s HashWithIndifferentAccess and Ruby’s Hash ?
The main difference between Ruby's Hash
and ActiveSupport's HashWithIndifferentAccess
is that HashWithIndifferentAccess
allows you to access keys using either strings or symbols interchangeably, while in a regular Hash
, strings and symbols are considered different keys[1][2][3].
For example, with a regular Hash
:
framework = { name: 'Ruby on Rails', language: 'Ruby' }
framework[:name] # "Ruby on Rails"
framework['language'] # nil
Accessing the key with a string returns nil
because the key was defined using a symbol.
With HashWithIndifferentAccess
, you can access keys consistently regardless of whether you use a string or symbol[2][3]:
require "active_support/hash_with_indifferent_access"
framework = ActiveSupport::HashWithIndifferentAccess.new
framework[:name] = 'Ruby on Rails'
puts framework[:name] # Ruby on Rails
puts framework['name'] # Ruby on Rails
HashWithIndifferentAccess
is commonly used in Rub...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào