Codecademy Logo

Hashes and Symbols

Ruby Symbols

In Ruby, symbols are immutable names primarily used as hash keys or for referencing method names.

my_bologna = { :first_name => "Oscar", :second_name => "Meyer", :slices => 12 } puts my_bologna[:second_name] # => Meyer #Symbols must be valid Ruby variable names and always start with a colon (:).

Ruby Hashes, Symbols, & Values

In Ruby hashes, key symbols and their values can be defined in either of two ways, using a => or : to separate symbol keys from values.

my_progress = { :program => "Codecademy", :language => "Ruby", :enthusiastic? => true } #Key symbols and their values can be defined with a =>, also known as a hash rocket. my_progress = { program: "Codecademy", language: "Ruby", enthusiastic?: true } #Key symbols and their values can also be defined with the colon (:) at the end of the symbol followed by its value.

Ruby .select Method

In Ruby, the .select method can be used to grab specific values from a hash that meet a certain criteria.

olympic_trials = { Sally: 9.58, John: 9.69, Bob: 14.91 } { |name, time| time < 10.05 } #The example above returns {:Sally=>9.58, :John=>9.69} since Sally and John are the only keys whose values meet the time < 10.05 criteria.

Ruby .each_key & .each_value

In Ruby, the .each_key and .each_value methods are used to iterate over only the keys or only the values in a hash.

eren_jaeger = { age: 15, enemy: "titans", branch: "Survey Corps" } eren_jaeger.each_key { |key| puts key } #Output: #age #enemy #branch eren_jaeger.each_value { |value| puts value } #Output: #15 #titans #Survey Corps