Câu hỏi phỏng vấn Ruby on Rails
Câu hỏi

Can you explain the difference between ActiveSupport’s HashWithIndifferentAccess and Ruby’s Hash ?

Câu trả lời

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:

ruby Copy
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]:

ruby Copy
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

middle

Gợi ý câu hỏi phỏng vấn

junior

What Is The Difference Between Nil And False In Ruby?

expert

What is the best thing which you find about the Ruby on Rail so far?

middle

Mention what is the difference between the Observers and Callbacks in Ruby on Rails?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào