Last active
May 30, 2018 17:51
-
-
Save cpkenn09y/a72d93b9b377f25358cb43932cec9a23 to your computer and use it in GitHub Desktop.
Ruby Hashes Explained
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<<-OLIVER_QUESTION_20180530 | |
Oliver's Question: what does "validate" mean here? | |
self.save(validate: false) | |
I'm trying to understand what var: means (specifically, the colon symbol) | |
Is this specifying the name of the parameter that the value is to be matched up with? | |
OLIVER_QUESTION_20180530 | |
# -- LESSON: In Ruby, a hash can use Strings (eg. "almond", "twix") or symbols (eg. :almond, :peanut) as keys. -- # | |
## 1. Here is an example of using Strings as its keys | |
hash_a = { "almond" => 1111, "peanut" => 2222 } | |
hash_b = { "mango" => 1111, "pear" => 2222 } | |
## NOTE: hash_a's keys are "almond", "peanut". | |
## NOTE: hash_b's keys are "mango", "pear" | |
## 2. Here is an example of a hash using symbols as its keys | |
hash_a1 = { :almond => 1111, :peanut => 2222 } | |
hash_b2 = { :mango => 1111, :pear => 2222 } | |
## NOTE: hash_a's keys are "almond", "peanut". | |
## NOTE: hash_b's keys are "mango", "pear" | |
## 3. Eventually a shorthand way was created to represent hashes containing symbols | |
hash_a1_equivalent = { almond: 1111, peanut: 2222 } # equivalent to { :almond => 1111, :peanut => 2222 } | |
hash_b2_equivalent = { mango: 1111, pear: 2222 } # equivalent to { :mango => 1111, :pear => 2222 } | |
## 4. Within Rails there is a construct called a HashWithIndifferentAccess. This allows you to have a hash that can be accessed via Strings or Keys. | |
# * NOTE: This part of the code will only work within a Rails context. | |
hash_with_indifferent_access = HashWithIndifferentAccess.new({a: 1, b: 2, "c" => 3, :d => 4}) | |
hash_with_indifferent_access[:a] #=> 1 | |
hash_with_indifferent_access["a"] #=> 1 | |
hash_with_indifferent_access[:b] #=> 2 | |
hash_with_indifferent_access["b"] #=> 2 | |
hash_with_indifferent_access[:c] #=> 3 | |
hash_with_indifferent_access["c"] #=> 3 | |
hash_with_indifferent_access[:d] #=> 4 | |
hash_with_indifferent_access["d"] #=> 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment