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

senior

What is ActiveJob ? When should we use it?

expert

What is Asset Pipeline?

junior

Mention what are the positive aspects of Rails?

Bình luận

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

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