Ruby Quiz (Easy) #8

question mark

Question

What would be the output of this code snippet?

Hint: note the type of the key in the hash and the type of the key when accessing the hash.

 

Solution

The output is nil because the hash is defined using symbols, and the access to it was done using a string.

Rails’ active_support introduced a class called HashWithIndifferentAccess (a subclass of Hash), which, according to the class’ doc:

[…] we only have it so that people can write params[:key] instead of params[‘key’] and they get the same value for both keys.

Referring back to the example above, we could get what we want (indifference between symbol or string hash access) with:

 

which would print "ruby".

 

Advertisements

One comment

  1. We implemented something we call Dash (Defensio Hash) in Defensio. This is all the same for us:d[:hello_world]d[“hello_world]d[“hello-world”]Dash is based on Mash, Merb’s Hash (I guess it’s where the name comes from). Loving it 🙂

Got a comment?

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: