Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Symbols and Hashes Intro

Symbols and Hashes Intro

Intro to Symbols and Hashes

Saurabh Bhatia

April 25, 2013
Tweet

More Decks by Saurabh Bhatia

Other Decks in Technology

Transcript

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

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

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

    • my_symbol = :foo_bar – right • attr_accessor :foo_bar • my_symbol = :foo_bar.to_s
  4. hash • Data structure – collection of key value pairs

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

    • animals["dog"] = "bark" • pry(main)> animals => {"dog"=>"bark", "cat"=>"purr"}
  6. • 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
  7. 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
  8. 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] }]