ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Ruby] exercise _ Hash To Pairs
    coding for food 2022. 8. 5. 12:57

    Write a method hash_to_pairs that takes in a hash and returns a 2D array representing each key-value pair of the hash.

    def hash_to_pairs(hash)
    
    end
    
    
    print hash_to_pairs({"name"=>"skateboard", "wheels"=>4, "weight"=>"7.5 lbs"}) #=> [["name", "skateboard"], ["wheels", 4], ["weight", "7.5 lbs"]]
    puts
    
    
    print hash_to_pairs({"kingdom"=>"animalia", "genus"=>"canis", "breed"=>"German Shepherd"}) #=> [["kingdom", "animalia"], ["genus", "canis"], ["breed", "German Shepherd"]]
    puts

     

    my code 

    def hash_to_pairs(hash)
      pair = []
      
      hash.each do |key, value|
        pair << [key, value]
      end
    
      return pair
    end
    
    
    print hash_to_pairs({"name"=>"skateboard", "wheels"=>4, "weight"=>"7.5 lbs"}) #=> [["name", "skateboard"], ["wheels", 4], ["weight", "7.5 lbs"]]
    puts
    
    
    print hash_to_pairs({"kingdom"=>"animalia", "genus"=>"canis", "breed"=>"German Shepherd"}) #=> [["kingdom", "animalia"], ["genus", "canis"], ["breed", "German Shepherd"]]
    puts

    solution 

    def hash_to_pairs(hash)
      pairs = []
      hash.each { |key, val| pairs << [key, val] }
      return pairs
    end
    
    print hash_to_pairs({"name"=>"skateboard", "wheels"=>4, "weight"=>"7.5 lbs"}) #=> [["name", "skateboard"], ["wheels", 4], ["weight", "7.5 lbs"]]
    puts
    
    print hash_to_pairs({"kingdom"=>"animalia", "genus"=>"canis", "breed"=>"German Shepherd"}) #=> [["kingdom", "animalia"], ["genus", "canis"], ["breed", "German Shepherd"]]
    puts
Designed by Tistory.