Advertisement
karlakmkj

Hashes & Arrays

Sep 1st, 2021
464
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.03 KB | None | 0 0
  1. # Hashes are sort of like JavaScript objects or Python dictionaries in storing key value pairs.
  2.  
  3. # 1st way to create hashes
  4. pets = {
  5.   "Stevie" => "cat",
  6.   "Bowser" => "hamster",
  7.   "Kevin Sorbo" => "fish"
  8. }
  9.  
  10. # print pets hashes using .each
  11. pets.each { |x, y| puts "#{x}: #{y}" }
  12.  
  13. # 2nd way to create using the Hash keyword with new
  14. fruits = Hash.new
  15. fruits["red"] = "apple"  # add each key value pair individually
  16. fruits["green"] = "pear"
  17. fruits["yellow"] = "mango"
  18.  
  19. # print using .each and do
  20. # When iterating over hashes, we need two placeholder variables to represent each key/value pair.
  21. fruits.each do |color, fruit|
  22.   puts "#{color}: #{fruit}"
  23. end
  24.  
  25. # Array type 1
  26. languages = ["HTML", "CSS", "JavaScript", "Python", "Ruby"]
  27.  
  28. languages.each{ |element| puts element}
  29.  
  30. # Array type 2 - 2D form
  31. s = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]]
  32.  
  33. # to print each element in each sub array, put them inside the curly brackets
  34. s.each{ |sub_array|
  35.   sub_array.each {|x|
  36.     puts x
  37.   }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement