Symbols and Hashes Intro

Symbols and Hashes Intro

Intro to Symbols and Hashes

E0fe062ff7f5d75b8e13773340370db5?s=128

Saurabh Bhatia

April 25, 2013
Tweet

Transcript

  1. Strings and Hashes

  2. What is it ? • Symbol is something used to

    represent a string. • A more memory efficient and descriptive way to do things.
  3. How does it look ? Colon followed by a non-quoted

    string - :symbol Or Colon followed by quoted string - :'this is another symbol'
  4. Assigning stuff to symbols • :my_symbol = “foo_bar” - wrong

    • my_symbol = :foo_bar – right • attr_accessor :foo_bar • my_symbol = :foo_bar.to_s
  5. Symbols are immutable

  6. hash • Data structure – collection of key value pairs

    • Indexing via keys of object _type • Randomly ordered
  7. What does it look like ? • animals = Hash.new

    • animals["dog"] = "bark" • pry(main)> animals => {"dog"=>"bark", "cat"=>"purr"}
  8. • Iterating over an array • animal_farm.each do |a| puts

    a end • Iterating over a hash • animals.each do |k,v| puts “#{k} and #{v} end
  9. exercise • Create a hash to represent currencies eg USA

    => usd , UK => gbp, JAPAN => yen • Display all the currencies • Replace all the name of countries with their short codes eg US -> US, JAPAN –> JP, UK -> UK
  10. Solution • currencies = { “USA” => “usd” , “UK”

    => “gbp”, “JAPAN” => “yen” } • new_currencies = {"US" => "usd", "UK" => "gbp", “JP” => “yen”} • Hash[currencies.map {|k, v| [new_currencies[k], v] }]